Saturday, May 26, 2007

How to read a singly linked list backwards?

Use Recursion.

14 comments:

  1. This is no possible in case of singale linked list because we don't have back address

    ReplyDelete
  2. One way to do this is using recursive operation

    Other way is through LIFO data structure

    ReplyDelete
  3. Ya I agree, we can use Stack, and push the elements in stack. and after the POP it till the stack is empty.

    ReplyDelete
  4. Can we not write recursive program like

    void PrintListFromBack(LIST * Root)
    {
    if(!Root)
    return;
    else
    if(Root->next)
    PrintListFromBack(Root->Next);

    printf("%d", Root->info);
    }

    ReplyDelete
  5. 1] Stack solution
    2] Recursive function
    3] Reverse list and print

    ReplyDelete
  6. build another list.

    ReplyDelete
  7. //pass head as the argument
    int print_reverse(list *ptr){
    if(ptr==NULL)
    return 0;
    else{
    print_reverse(ptr->link);
    printf(" %d ",ptr->data);
    }
    return 0;
    }

    ReplyDelete
  8. first reverse the list and read

    ReplyDelete
  9. algorithm to reverse a singly linked list:

    top=null
    while(head!=null)
    {
    temp = start
    start = start.next
    temp.next = top
    top = temp
    }

    correct, no?

    ReplyDelete
  10. CORRECT SOLUTION IS

    void PrintListFromBack(LIST * Root)
    {
    if(!Root)
    return;
    else
    if(Root->next)
    PrintListFromBack(Root->Next);

    printf("%d", Root->info);
    }

    ReplyDelete
  11. Copied from cracktheinterview. word to word

    ReplyDelete
  12. The solution given with the function PrintListFromBack is a good one and make sense.

    ReplyDelete
  13. one way void readfrmbck(struct node *start)
    {
    if(start==NULL)
    return;

    //printf("%d",start->data);
    readfrmbck(start->next);
    printf("%d",start->data);
    }to solve this question is:

    ReplyDelete
  14. one way to solve this is:
    void readfrmbck(struct node *start)
    {
    if(start==NULL)
    return;

    //printf("%d",start->data);
    readfrmbck(start->next);
    printf("%d",start->data);
    }

    ReplyDelete