Thursday 2 August 2012

How to read a singly linked list backwards (or) how to reverse a single linked list

solution1--reverse the list and read it..

struct node* reverseList(struct node* head)
{
struct node *ptr1,*ptr2,*first,*last;
if(head==NULL)
    return NULL:
first=head;
while(head!=NULL)
{
    ptr1=head;
    ptr2=head->link;
    if(first==head)
         ptr1->link=NULL;
  
    ptr2->link=ptr1;
    head=ptr2;
    if(head->link==NULL)
        first=head;
}
return first;
}


solution2 : push the elements into the stack and then read the elements

2 comments:

  1. nice code...also another good one here:

    Reverse a linked list

    ReplyDelete
  2. there is also a code for reverse of single linked list........
    void readfrmbck(struct node *start)
    {
    if(start==NULL)
    return;

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

    ReplyDelete