A question on linked lists

Write your question here.
How come that 1 program gives 2 different outputs?
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
  Put the code you need help with here.
Here is my program:
#include <iostream>
using namespace std;

int main() {
using namespace std; 	
	struct nodeType
	{
		int info;
		nodeType *link;
	} ;
typedef nodeType *nodePtr;

	nodePtr ptr, list;
	list = new nodeType;
	list->info = 20;
	ptr = new nodeType;
	ptr ->info = 28;
	ptr->link = NULL;
	list->link = ptr;
	ptr = new nodeType;
	ptr->info = 30;
	ptr->link = list;
    list = ptr;
	ptr = new nodeType;
	ptr->info = 42;
	ptr->link = list->link;
	list->link = ptr;
	while(ptr != NULL)
	{
		cout << ptr->info << endl;
		ptr = ptr->link;
		  }  	
}

Here is my output:
42
20
28
The node with info = 30 is lost.

Here is my tutors output from UNISA(University of South Africa)
30
42
20
28
The node with info = 30 is the first one out.

Please assist.
line number 28 is loosing your data of 30
ptr->link = list->link;
ptr ->link is containing list->link which keep the address of node of value 20

so to get the complete list
ptr->link = list;

line number 29 is not required if you are printing only ptr value

I appreciate you help very much sylphsang. Now I am no longer loosing any node but my output is now:
42
30
20
28
which is still different from my tutors output which is listed above as
30
42
20
28

Can you clear that part a bit. Linked lists can be very confusing.
I really have a doubt whether ur tutor is having a same code. Definitely there is some other code ur tutor is having which is linking the node in different order.if you want that code i will write the same
I will be happy to see such code. It would be very interesting.
with the current flow of code its not possible but if the info of ptr->info = 30; and ptr->info = 42; if its interchanged then the ur tutor order will come.
I did that and it worked. Thanks very much sylphsang
Topic archived. No new replies allowed.