Thursday, September 2, 2010

C Program to reverse a " Linked List "

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


struct node
{
    int data;
    struct node *link;
};
void append(struct node**,int);
void display(struct node*);
void reverse(struct node **);
void main()
{
   struct node *head;
   clrscr();
   head=NULL;
   append(&head,5);
   append(&head,6);
   append(&head,7);
   append(&head,8);
   display(head);
   reverse(&head);
   display(head);
   getch();
}

void append(struct node **q,int num)
{
   struct node *temp,*r;
   temp=*q;

   if(temp==NULL)  /* If list is empty , create first node */
   {
       temp=(struct node*)malloc(sizeof(struct node));
       temp->data=num;
       temp->link=NULL;
       *q=temp;
   }
   else
   {
      temp=*q;
      while(temp->link !=NULL)
      temp=temp->link;

      r=(struct node*)malloc(sizeof(struct node));
      r->data=num;
      r->link=NULL;
      temp->link=r;
   }
}
void display(struct node *start)
{
   printf("\n");
   printf(" The Linked List is :\n");
   /* Traverse the entire linked list */
   while(start != NULL)
   {
      printf("   %d",start->data);
      start=start->link;
   }
}
void reverse(struct node **x)
{
  struct node *q,*r,*s;
  q=*x;
  r=NULL;

  /* Traverse the enitre linked list */
  while(q != NULL)
  {
      s=r;
      r=q;
      q=q->link;
      r->link=s;
  }
  *x=r;
}

No comments:

Post a Comment