兩個多項式相加 ( C++ )

來源:互聯網
上載者:User

標籤: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++ )

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.