Hey, just wanna say thanks in advance with the help.

void backwards(struct node *headp){

int n=0; /* length */
int i,j; /* counters */

struct node *p=headp;
/* find length */
while( p->next !=NULL )
{ n++;
p=p->next;
}
printf(“%d\n”, p->number); /* print TAIL */
for(i=n-1; i>=1; i--)
{ /* initialize p to point to HEAD; then find ith node */
p=headp;
for(j=1; j<=i; j++)
{ p=p->next; }
printf(“%d\n”, p->number);
}
}

This code is suppose to printout a linked list backwards, so the part i dont understand is the last part the two loops... can someone explain in detail wats goin on? The first pass (say n=5), when i =4, it sets the p pointer to headp and when u go into the second loop it prints out linked list 1 2 3 and stops at 4. Then it exits and enters the first loop again where i = 3, then it prints lists 1 2 3. And then 1 2 and finally 1. Am i reading this code right or am i completely off path? I mean this code is suppose to print linked list backwards... ANy help appreciated. Also there is nothing wrong with the code, i got it from Instructor.

The code you posted looks like it should just print the number stored at the last node visited in each smaller and smaller walk through the list. If you are seeing 1 2 3 4 1 2 3 1 2 1, then you probably have moved the output statement inside the j loop's body.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.