Saturday 14 September 2013

reverse doubly linked list

#include<stdio.h>
#include<conio.h>

typedef struct node node;

struct node
{
       int info;
       node *pre;
       node *next;
};

node *head=NULL;

node *reverse(node *ptr)
{
   
                   if(ptr->next->next==NULL)
                   {
                                   head=ptr->next;
                                   ptr->next->next=ptr;        
                   }
                   else
                   {
                                   reverse(ptr->next);
                                   ptr->next->next=ptr;
                   }
                   return ptr;
}

main()
{
      FILE *f=fopen("hinput.txt","r");
      char c[5];
      node *ptr,*temp;
      while(fscanf(f,"%s",c)!=EOF)
      {
               ptr=(node*)malloc(sizeof(node));
               ptr->info=atoi(c);    
                                 
               if(head==NULL)
               {
                            head=ptr;
                            ptr->pre=NULL;
                            ptr->next=NULL;
                            temp=head;
               }                  
               else
               {
                            ptr->pre=temp;
                            ptr->next=NULL;
                            temp->next=ptr;
                            temp=temp->next;    
               }
      }
      temp=head;
      while(temp!=NULL)
      {
                       printf("%d\n",temp->info);
                       temp=temp->next;
      }
     
      temp=reverse(head);
      temp->next=NULL;
      temp=head;
      while(temp!=NULL)
      {
                       printf("%d\n",temp->info);
                       temp=temp->next;
      }
     
      getch();
}

No comments:

Post a Comment

Have some problem with this code? or Request the code you want if you cant find it in Blog Archive.