Advertisement
mhrabbi

Reverse a LinkedList

Oct 21st, 2019
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.36 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. struct node
  4. {
  5.     int data;
  6.     struct node *next;
  7. }*head;
  8.  
  9. int main()
  10. {
  11.     int n;
  12.     printf("Enter total number of node: ");
  13.     scanf("%d",&n);
  14.  
  15.     createList(n);
  16.  
  17.     printf("\nList is\n ");
  18.  
  19.     displaylist();
  20.  
  21.     printf("\nReversed List is: \n");
  22.     reverseList();
  23.  
  24.     displaylist();
  25.  
  26.     return 0;
  27. }
  28. void createList(int n)
  29. {
  30.     struct node *p,*temp;
  31.     int i,data;
  32.  
  33.     temp=(struct node *)malloc(sizeof(struct node));
  34.  
  35.     printf("Enter the data of the node 1: ");
  36.     scanf("%d",&data);
  37.  
  38.     temp->data=data;
  39.     temp->next=NULL;
  40.  
  41.     p=temp;
  42.     head=temp;
  43.  
  44.     for(i=2;i<=n;i++)
  45.     {
  46.         temp=(struct node *)malloc(sizeof(struct node));
  47.  
  48.         printf("Enter the data of the node %d: ",i);
  49.         scanf("%d",&data);
  50.  
  51.         temp->data=data;
  52.         temp->next=NULL;
  53.  
  54.         p->next=temp;
  55.         p=p->next;
  56.  
  57.     }
  58.  
  59. }
  60.  
  61. void displaylist()
  62. {
  63.     struct node *temp;
  64.     temp=head;
  65.  
  66.     while(temp!=NULL)
  67.     {
  68.         printf("\n%d",temp->data);
  69.         temp=temp->next;
  70.     }
  71. }
  72.  void reverseList()
  73.  {
  74.      struct node *current,*prev,*next;
  75.      current=head;
  76.      prev=NULL;
  77.  
  78.      while(current != NULL)
  79.      {
  80.          next=current->next;
  81.          current->next=prev;
  82.  
  83.          prev=current;
  84.          current=next;
  85.  
  86.  
  87.      }
  88.      head=prev;
  89.  }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement