Wednesday 11 February 2015

Program to invert elements of a singly linked list.


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct node
{
      int data;
      struct node *next;
}node;
main()
{
      node *head,*p,*q,*r;
      int n,i,j;
      printf("N=");
      scanf("%d",&n);
      head=(node *)malloc(sizeof(node));
      scanf("%d",&head->data);
      p=head;
      for(i=1;i<n;i++)
      {
            p->next=(node *)malloc(sizeof(node));
            p=p->next;
            scanf("%d",&p->data);
            p->next=NULL;
      }
      p=head;
      printf("\n\nThe linked list 1 is=\n\nHead");
      while(p!=NULL)
      {
            printf("->%d",p->data);
            p=p->next;
      }
      p=NULL;
      q=head;
      //r=q->next;
      printf("\n\nThe inversed linked list is=\n\nHead");
      while(q!=NULL)
      {
            r=p;
            p=q;
            q=q->next;
            p->next=r;
      }
      head=p;
      while(p!=NULL)
      {
            printf("->%d",p->data);
            p=p->next;
      }
      getch();
}
     

      

No comments:

Post a Comment