Problem adding two linked lists (objects)

Hi guys,

Need a little help. Here's the code.

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
struct Node{
	int number;
	Node* next;

};

class Link{

public:
	Link(){first=NULL;}
	//Link(const Link& l){}
	void input(int n){
		Node *dummy, *temp;

		temp=new Node;
		temp->number=n;
		temp->next=NULL;

		if(first==NULL){
			first=temp;
		}
		else{
			dummy=first;
			while(dummy->next!=NULL)
				dummy=dummy->next;
			dummy->next=temp;
		}
	}
	Link add(Link l){//problem start here
		Node *addition=first;
		while(addition->next!=NULL){
			addition->number=l.first->number+first->number;
			addition=addition->next;
		}
		return Link(addition);//problem ends here
	}
	void print(){
		Node *temp=first;
		while(temp!=NULL){
			if(temp->next!=NULL)
				cout<<temp->number<<",";
			else
				cout<<temp->number;
			temp=temp->next;
		}
		
	}
private:
	Node *first;
};

int main(){
	Link list1, list2;

	list1.input(4);
	list1.input(1);
	list1.input(5);
	list1.input(8);
	list1.input(4);
	cout<<"First list: =";
	list1.print();
	cout<<endl<<endl;


	list2.input(1);
	list2.input(1);
	list2.input(1);
	list2.input(1);
	list2.input(1);
	cout<<"Second list: =";
	list2.print();
	cout<<endl<<endl;

	Link addition=list1.add(list2);
	addition.print();

	_getch();
	return 0;
}


I am trying to make a polynomial class using link lists, and my first step is attempting to add to lists of the same size (for simplicity). However, adding linked lists does not appear to be as easy as adding two arrays. Could someone please tell me what I am doing wrong. I suspect it might have to do with the copy constructor which I am not sure how it should behave, look etc.

Thanks,

Mike
You kind of got the copy constructor right, I mean the signature.
Because the empty body is definitely wrong. You don't seem to need it yet, anyway.

You also have memory leaks, because you don't manually delete that which you manually new'd. (You're supposed to do this in the destructors.)

I could try to explain why return Link(addition); doesn't work, but it doesn't matter, as soon as you realize you don't need to do that.

And for the love of Cola, leave some spaces here and there, man.

1
2
3
4
5
6
7
8
9
10
11
	Link add(Link l){
		Node *addition1=first;
		Node *addition2=l.first;
		Link r; // resulting list
		while(addition1!=NULL){
			r.input(addition1->number+addition2->number);
			addition1=addition1->next;
			addition2=addition2->next;
		}
		return r;
	}
Damn, thanks a lot, works really well! I see now that I have to create those two nodes for addition, pointing to first, and then we can start.

Thanks again!

Mike
Topic archived. No new replies allowed.