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++;
printf(ā€œ%d\nā€, p->number); /* print TAIL */
for(i=n-1; i>=1; i--)
{ /* initialize p to point to HEAD; then find ith node */
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.

9 Years
Discussion Span
Last Post by vmanes

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.