-
Notifications
You must be signed in to change notification settings - Fork 0
/
polyAdder.cpp
99 lines (89 loc) · 2.36 KB
/
polyAdder.cpp
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
using namespace std;
struct node {
int coeff;
int power;
node* next;
};
void insert(node **head,node **rear,int ce,int power) {
node* newNode = new node;
if(!newNode) {
cout<<"Sorry! Memory allocation error"<<endl;
return;
}
newNode->coeff = ce;
newNode->power = power;
if(*head == NULL) {
newNode->next = NULL;
*head = newNode;
*rear = newNode;
}
else {
(*rear)->next = newNode;
newNode->next = NULL;
*rear = newNode;
}
}
void traversal(node **head) {
node *temp = *head;
cout<<"C(x) = A(x) + B(x) = "<<endl;
while(temp!=NULL) {
cout<<temp->coeff<<" "<<temp->power<<endl;
temp = temp->next;
}
}
void deleteList(node **head) {
node* p = *head;
if(p == NULL)
return;
while(p->next != NULL) {
node *temp = p->next;
p->next = temp->next;
delete temp;
}
delete p;
}
int main() {
int ce,pw;
node *headA,*headB,*headC,*rearA,*rearB,*rearC;
headA = headB = headC = rearA = rearB = rearC = NULL;
cout<<"Enter A(x)"<<endl;
do {
cin>>ce>>pw;
insert(&headA,&rearA,ce,pw);
}while(pw!=0);
cout<<"Enter B(x)"<<endl;
do {
cin>>ce>>pw;
insert(&headB,&rearB,ce,pw);
}while(pw!=0);
node *cursorA = headA,*cursorB = headB;
while(cursorA != NULL && cursorB != NULL) {
if(cursorA->power > cursorB->power) {
insert(&headC,&rearC,cursorA->coeff,cursorA->power);
cursorA = cursorA->next;
}
else if(cursorA->power < cursorB->power) {
insert(&headC,&rearC,cursorB->coeff,cursorB->power);
cursorB = cursorB->next;
}
else if(cursorA->coeff + cursorB->coeff != 0) {
insert(&headC,&rearC,cursorA->coeff + cursorB->coeff,cursorA->power);
cursorA = cursorA->next;
cursorB = cursorB->next;
}
}
while(cursorA != NULL) {
insert(&headC,&rearC,cursorA->coeff,cursorA->power);
cursorA = cursorA->next;
}
while(cursorB != NULL) {
insert(&headC,&rearC,cursorB->coeff,cursorB->power);
cursorB = cursorB->next;
}
traversal(&headC);
deleteList(&headA);
deleteList(&headB);
deleteList(&headC);
return 0;
}