Linked list and function

Hi all

i can't understand the output of this code

1
2
3
4
5
6
7
8
node* test(node* &X) {
	node *t=X;
	t=t->next;
	node*k=X->next->next->next;
	X=k->next;
	k->next=0;
	return t;
}


Assuming X is a linked list and its struct is defined:

struct node{int info; node* next; nodo(int a=0, nodo* b=0){info=a; next=b;}};

And X has following nodes value:

1->2->3->4->5->6->7->8->9

And of course if i print X after text the remaining list is:

4->5->6->7->8->9

Because of X=k->next;

The thing that i don't undesrtand is why after k->next=0; X doesn't change but if i print t the output is
2->3->4
Look like k->next=0 modify even t but not X, could someone please explain me?

Thanks
Does this help?
1
2
3
4
5
6
7
8
9
node* test( node* & X )
{
  node* t = X;
  t = t->next;
  node* k = X->next->next->next;
  X = k->next;
  k->next = 0;
  return t;
}
1->2->3->4->5->6->7->8->9
X
t
   t
         k
            X
1->2->3->4  5->6->7->8->9


PS 1. If X was the only pointer to 1, then after the function nothing points to 1 any more: a memory leak.

PS 2. If list does not have enough elements, then the function has undefined results.
Last edited on
Topic archived. No new replies allowed.