What is the linked list doing?

1
2
3
4
5
6
7
8
9
10
11
12
struct Node{
    int data;
    Node *next;
};
Node *n1, *n2;
n1 = new Node;
n2 = new Node;
n1->data = 1;
n2->data = 2;
n1->next = n2;
n2->next = n1;
n2->next->next->data = 7;

I understand the code until n1->next
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// create struct Node with 2 fields: Int 'data' and pointer to Node "next"
struct Node{
    int data;
    Node *next;
};
Node *n1, *n2; // declare two pointers to Node, 'n1' and 'n2'
n1 = new Node; // make new Node and have n1 point to it
n2 = new Node; // make new Node and have n2 point to it
n1->data = 1; // data field of Node that n1 is pointing to = 1
n2->data = 2;// data field of Node that n2 is pointing to = 2
n1->next = n2; // n1's next pointer points to n2
n2->next = n1; // n2's next pointer points to n1
// at this point we have two nodes, and each one's next pointer point to the other
// you can picture it as a circle. n1 to n2, to n1, to n2 ....


//Two next pointers used, meaning we have to start at node n2, 
// then move up two nodes, then set that nodes data field to 7.
//n2->next (that brings you to n1) ->next (brings you to n2)
// -> data = 7 (n2's data field is now 7)
n2->next->next->data = 7; 
Last edited on
from the struct Node you create 2 objects: n1 and n2.

a Note object have 2 members:
int data
Note* next

n1 data is set to 1
n2 data is set to 2
n1 is linked with his next pointer to n2
n2 is linked with his next pointer to n1

n2->next->next->data = 7
explaining:
n2->next is pointing to n1
n2->next->next is pointing to n1 and than to n2

so
n2->next->next->data = 7

is the same as
n2->data = 7

which set the data member of object n2 to 7



Topic archived. No new replies allowed.