標籤:this dex 並且 head 元素 ffffff 相等 訪問 else
實現兩個多項式進行相加 不開闢空間 ( 這要求實現進行相加,代價為兩個原鏈表將被修改)
分析:
this>other 就把other當前結點放置在this之前
this<other 就this當前結點前移一位,並且後繼也前移一位
this==other 求和為0就刪除,並全部前移一位,不等就刪除other中的當前結點並前移
注意:
必須注意 n 作為始終指向 mHead, n->next 始終指向other鏈表的下一個結點,所以修改了other鏈表時候必須注意 n->next的指向
有些書上 C語言實現的多項式之和,如果 修改對應的代碼植入於C++中,能夠得到正確結果,但是 C++ 的解構函式將會出錯,故此要將 other 表中的指標 n 指向明確
1 void Link::Add( Node * mHead) { 2 Node * ph = Head->Next; 3 Node * pm = mHead->Next; 4 Node * m = Head; //作為一個標記,標記this上一次訪問的結點 5 Node * n = mHead; // n 始終指向頭結點,並且 n->next指向 pm 的下一個結點元素 6 7 while( ph!=NULL && pm!=NULL) { // 判斷當 A 或 B 兩個鏈表不為空白時 8 if( ph->Index>pm->Index) { //this>other ,將other的第一個結點插入到 this當前結點之前 9 n->Next = pm->Next; // 讓 n 的 next指標指向 pm的下一個結點,10 m->Next = pm;11 m = pm;12 m->Next = ph;13 pm = n->Next; // 上述將 pm 插入時,將 pm 指向下一個結點,即 n->enxt14 }15 else if( ph->Index<pm->Index) { //this<other 只需要將this的結點後移一位,注意 m 始終未 this的上一個結點16 m = ph;17 ph = ph->Next;18 }19 else { //this==other20 Node * tem;21 if( ph->Ratio+pm->Ratio==0) { // 求和為0 將this的當前結點刪除,並且後移一位22 tem = ph;23 ph = ph->Next;24 Delete(tem);25 }26 else { //求和不為0, 將係數相加27 ph->Ratio = ph->Ratio+pm->Ratio;28 } // 當相等時,都要刪除掉other的當前結點,並後移一位29 tem = pm;30 pm = pm->Next;31 n->Next = pm; //32 Delete(tem); 33 }34 }35 if( ph==NULL) { // 由於當other > this時,只將this後移,所以 pm 為空白表示都插入進去,不為空白時,36 m->Next = pm; // 表示this的鏈表為空白了,所以將other剩下的鏈表插入 this 的表尾,即 n 指向最後一個結點 n->next正好是表尾指標37 n->Next = NULL; // 設定表尾為空白38 }39 }40 void Link::Delete(Node * tem) { // 刪除結點 tem41 delete tem;42 }
兩個多項式相加 ( C++ )