Pages

Monday, 26 August 2013

Reverse a Singly Linked List

Hi, This program is about implementation of Reverse a singly linked list.

If you have any doubt regarding this program or any concept of C then please send me at khimanichirag@gmail.com or post a comment.

suggestion always appreciable


      #include<stdio.h>  
      #include<conio.h>  
      void reverse();  
      typedef struct node  
      {  
            int data;  
            struct node *link;  
      }node;  
      node *first=NULL,*last;  
      void main()  
      {  
           int i=0;  
           node *temp;  
           printf("Enter the link list data");  
            do  
            {  
                 clrscr();  
                  temp=(node*)malloc(sizeof(node));  
                 i++;  
                 if(first==NULL)  
                 {  
                        first=temp;  
                        last=temp;  
                        last->link=NULL;  
                 }  
                 else  
                 {  
                        last->link=temp;  
                        last=temp;  
                        last->link=NULL;  
                 }  
                  printf("\nEnter the %d element",i);  
                  scanf("%d",&(last->data));  
                  printf("\nYou want to enter more data(Y/N)");  
            }while(getch()=='y');  
            printf("\n\nYour link list is:");  
            temp=first;  
            while(temp!=NULL)  
            {  
                  printf("%d ",temp->data);  
                  temp=temp->link;  
            }  
            checkloop();  
      }  
      void checkloop()  
      {  
            int flag=0;  
            node *fast,*slow;  
            fast=first;  
            slow=first;  
            while(fast!=NULL && slow!=NULL)  
            {  
                   fast=(fast->link)->link;  
                   slow=slow->link;  
                   if(fast==slow)  
                   {  
                    flag=1;  
                   }  
            }  
            if(flag=1)  
           {  
                   printf("\nlink list contains loop");  
           }  
            else  
           {  
                   printf("\nloop nthi vo bhai");  
           }  
            temp=first;  
            first=last;  
            last=temp;  
            ptr=first;  
            if(ptr==NULL)  
            {  
                  printf("empty");  
            }  
            while(ptr!=NULL)  
            {  
                  printf("%d ",ptr->data);  
                  ptr=ptr->link;  
            }  
            getch();  
      }.