Drawing a dynamic structure

Hi,
do you know how a drawing of this structure would look like. If it was to be drawn on a piece of paper. Each element has to have a data value. Next field should be connected with field it points at with an arrow.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  struct elem
{ char data;
  struct elem *next;
} *p, *q;

int main()
{
int i = 0;
p = new elem;
p->next = p;
p->data= i;

for(i = 1; i <= 2; i++)
  {
   q = new elem;
   q->data= i;
   q->next= p->next;
   p->next= q;
   p = q;
  }
}
I'm not sure what you ask, so I do guess: http://lmgtfy.com/?t=i&q=linked+list
That is what I was looking for but I'd like to see how this code would look like drawn.

This is one of the questions I have on my test.
You'll cut adrift elem object with data == 0 after the first iteration of the loop and lose access to it completely by the end of the loop:
step 1: 2 pointers p and p->next both pointing to elem object with data == 0
step 2: q(1) points to elem object with data == 1 and q(1)->next points to elem object with data == 0; p->next now points to elem object with data == 1 and p points to elem object with data == 1
So we have one pointer to elem object with data == 0, viz. q(1)->next and 3 pointers to the elem object with data == 1 viz. p, p->next and q(1) - notice q(1)->next is already starting to get cut off, if the loop ended here you could still access the object through q(1)->next but, as shown below, this will be lost in the next loop
step 3: q(2) points to elem object with data == 2 and q(2)->next points to elem object with data == 1. p->next points to elem object with data == 2 and p points to elem object with data == 2
So we have one pointer, q(1)->next, pointing to elem object with data == 0, two pointers, q(1) and q(2)->next pointing to elem object with data == 1 and three pointers (p, p->next and q(2)->next) pointing to elem object with data == 2. Of course q(2) is actually q in the program and as there is no linkage b/w q(1) next and any of the other pointers you cannot access elem object with data == 0 any longer
Here is a link to setting up a singly linked list:
http://www.cplusplus.com/forum/beginner/209045/#msg983899 and there will be many more on-line
Thanks for explaining it so thoroughly. Could you make a sketch of it in paint?
Topic archived. No new replies allowed.