Linked List, Addition between the 2 Expressions

Hi. Here is my source code asking the user to input 2 polynomial expressions. Now, I am stuck on how to do the addition for both expressions given by the user input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
  #include<iostream>
using namespace std;

class Node{
      public :
             int coef;
             int exp;
             Node *next;
      private:
      };
      
class List{
      public:
             List(){
                    head = NULL;
             }
             void insert(int x, int y){
                  Node *newNode = new Node;
                  newNode->coef = x;
                  newNode->exp = y;
                  newNode->next = NULL;
                  
                  if(head==NULL){
                                 head = newNode;
                  }
                  else{
                       Node *currNode = head;
                       while(currNode->next!=0){
                             currNode = currNode->next;
                       }
                       currNode->next = newNode;
                  }
             }
             void display(){
                  Node *currNode = head;
                  cout<<"\n\n\t";
                  while(currNode->next!=0){
                        //cout<<"Coef: "<<currNode->coef<<"\t"<<"Expo: "<<currNode->exp<<endl;
                        cout<<currNode->coef<<"X^"<<currNode->exp<< "+";
                        currNode = currNode->next;
                  }
                  cout<<currNode->coef<<"X^"<<currNode->exp<<endl;
                  //cout<<"Coef: "<<currNode->coef<<"\t"<<"Expo: "<<currNode->exp<<endl;
             }
      private:
              Node *head;              
      };

int main(){
    
    List seq1,seq2;
      
    int a,b,x,y;
    cout<<"Enter your expression 1: "<<endl;
    
    while(cin>>a>>b,a!=0&&b!=-1){
            seq1.insert(a,b);
    }
    seq1.display();
    cout<<endl;
    cout<<"Enter your expression 2: "<<endl;
    
    while(cin>>x>>y,x!=0&&y!=-1){
            seq2.insert(x,y);
	}
    seq2.display();
    
    return 0;
}
Add a method to your list ADT which will first check if the list contains 2 expressions, then it will add those expressions.

1
2
3
if (head != nullptr && head->next != nullptr) {
    ...
}
Thanks for the hint. So from the main I called a function which is add

seq.add(seq1,seq2)

Now in the class List, I put

1
2
3
4
void add(List seq1,List seq2){
if(head!=0 && head->next!=0) {
  ... }
}


Is it that one right?How can I add those expressions, is it based on their coefficient?
Last edited on
Topic archived. No new replies allowed.