kebria

Reverse a Single Linked List

Jun 13th, 2021
661
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Reverse a single linked list */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. struct node {
  6.     int data;
  7.     struct node *link;
  8. };
  9.  
  10. struct node *reverse(struct node *head)
  11. {
  12.     struct node *prev = NULL;
  13.     struct node *next = NULL;
  14.     while (head != NULL)
  15.     {
  16.         next = head->link;
  17.         head->link = prev;
  18.         prev = head;
  19.         head = next;
  20.     }
  21.     head = prev;
  22.     return head;
  23. }
  24.  
  25. int main()
  26. {
  27.     struct node *head = NULL;
  28.     head = malloc(sizeof(struct node));
  29.     head->data = 45;
  30.     head->link = NULL;
  31.  
  32.     struct node *current = NULL;
  33.     current = malloc(sizeof(struct node));
  34.     current->data = 90;
  35.     current->link = NULL;
  36.  
  37.     head->link = current;
  38.  
  39.     struct node *third = NULL;
  40.     third = malloc(sizeof(struct node));
  41.     third->data = 98;
  42.     third->link = NULL;
  43.  
  44.     head->link->link = third;
  45.     printf("Before Reversing: ");
  46.     printf("%d %d %d\n", head->data, current->data, third->data);
  47.  
  48.     printf("After Reversing: ");
  49.     struct node* ptr;
  50.     head = reverse(head);
  51.     ptr = head;
  52.     while (ptr != NULL)
  53.     {
  54.         printf("%d ", ptr->data);
  55.         ptr = ptr->link;
  56.     }
  57.     return 0;
  58. }
  59.  
  60.  
  61. /*
  62. Output:
  63. Before Reversing : 45 90 98
  64. After Reversing : 98 90 45
  65. */
  66.  
RAW Paste Data