數據結構-單鏈表-多項式相加


【問題描述】編寫一個程序用單鏈表存儲多項式,並實現兩個一元多項式A與B相加的函數。A,B剛開始是無序的,A與B之和按降序排列。例如:
                        多項式A:  1.2X^0  2.5X^1  3.2X^3  -2.5X^5
                        多項式B:  -1.2X^0  2.5X^1  3.2X^3   2.5X^5   5.4X^10
                        多項式A與B之和:5.4X^10  6.4X^3  5X^1

【輸入形式】任意兩個多項式A和B的項數及對應的系數和指數,要查詢的第幾項
【輸出形式】多項式中某一項的系數與指數,系數保留一位小數

【輸入樣例】
4 1.2 0 2.5 1 3.2 3 -2.5 5
5 -1.2 0 2.5 1 3.2 3 2.5 5 5.4 10
2

【輸出樣例】6.4  3

 

 1 #include<bits/stdc++.h>
 2 #include<stdlib.h>
 3 using namespace std;
 4 typedef long long ll;
 5 
 6 struct node{
 7     double data;
 8     int index;
 9     node* next;
10     node():index(0){}
11     node* operator [] (int n){
12         node* end=next;
13         while(end&&n--)end=end->next;
14         return end;
15     }
16     bool operator < (const node &t) const {
17         return index>t.index;
18     }
19     node operator * (node& t);
20 };
21 
22 void newList(node & head,int length){
23     node *a=new node[length];//這是這個函數的解釋node* operator [] (int n)P11行 申請空間的方式 new int[10]申請10個int類型的空間 再返回node指針類型
24     for(int i=0;i<length;++i)cin>>a[i].data>>a[i].index;
25          //a是node類型數組啊
26     sort(a,a+length);//p16行的函數解釋
27     node* end=&head;
28     for(int i=0;i<length;++i){
29         node* t=new node;
30         t->data=a[i].data;
31         t->index=a[i].index;
32         end->next=t;
33         end=t;
34     }//他這好像就特別簡單 end=xx  之后就申請了新節點 賦值 然后掛上去
35     delete[] a;
36 }
37 void show(node& head){//傳遞的這個是引用
38     node* end=head.next;//就還是這個類型 所以用的是.
39     while(end){
40         if(end->index==1) cout<<end->data<<"X^"<<(end->next?" + ":"\n");
41         else cout<<end->data<<"X^"<<end->index<<(end->next?" + ":"\n");//末尾加的這個的意思是 如果下一個節點還有 就+上 如果沒有就換行
42         end=end->next;
43     }
44 }
45 
46 ///多項式相加:
47 void combine(node& a, node& b){//傳遞的是引用
48     node* p,*q,*tail,*temp;
49     double s;
50     p=a.next;
51     q=b.next;
52     tail=&a;//就直接修改a鏈表了
53     while(p&&q){
54         if(p->index>q->index){
55             tail->next=p;tail=p;p=p->next;
56         }else if(p->index==q->index){
57             s=p->data+q->data;
58             if(s){
59                 p->data=s;
60                 tail->next=p; tail=p;p=p->next;
61                 temp=q;q=q->next;delete temp;
62             }else{
63                 temp=p;p=p->next;delete temp;
64                 temp=q;q=q->next;delete temp;
65             }//刪除沒有用的節點這點甚是符合朕心 厲害
66         }else{
67             tail->next=q; tail=q; q=q->next;
68         }
69     }
70     if(p)tail->next=p;
71     else tail->next=q;
72 }
73 
74 int main(){
75     node a,b;
76     int n1,n2;cin>>n1;
77     newList(a,n1);
78     cin>>n2;
79     newList(b,n2);
80     combine(a,b);
81 
82     cin>>n1;
83     cout<<fixed<<setprecision(1)<<a[n1-1]->data<<" "<<a[n1-1]->index<<endl;//這里可以這么騷也是因為p11行 牛逼
84     show(a);//給引用傳參數 就是傳本身 不是傳指針
85 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM