1

I had just tried out a program to reverse print a singular linked list.

Assume that the linked list is ready with 5 elements: 1->2->3->4->5

I had written a program to print in reverse order like: 5 4 3 2 1
But my program just prints as 5 4 3 2; the 1 is not printing. Why?

int Reverse_List(abc_t *pNode) {
    abc_t *pTemp;
    int count = 5;

    if (pNode->pNext != NULL) {
        pNode = pNode->pNext;
        Reverse_List(pNode);
        printf("The node is %d\n", pNode->a);
    }
}
4

2 回答 2

13

也许像这样

void Reverse_List(abc_t *pNode){
    if(pNode==NULL)
        return;

    Reverse_List(pNode->pNext);
    printf("The node is %d\n", pNode->a);
}
于 2013-06-06T11:39:16.353 回答
3

see how call works

you have list 1->2->3->4->5

now recursion start as

pnode = 1;    pnode->next=2; (!NULL)      (print 2)   
  pnode=2;    pnode->next=3; (!NULL)      (print 3)   
    pnode=3;    pnode->next=4 (!NULL)     (print 4)   
       pnode=4;   pnode->next=5 (!NULL)   (print 5)   
          pnode=5;   pnode->next==NULL

so here as you can see when you have one it will print two as you advance your pointer

for correct code see @BLUEPIXY's answer

于 2013-06-06T12:02:35.960 回答