kebria

Reversing the doubly linked list

Jun 16th, 2021 (edited)
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.53 KB | None | 0 0
  1. /* Reversing the doubly linked list */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. struct node {
  6.     struct node *prev;
  7.     int data;
  8.     struct node *next;
  9. };
  10.  
  11. struct node *addToEmpty(struct node *head, int data)
  12. {
  13.     struct node *temp = malloc(sizeof(struct node));
  14.  
  15.     temp->prev = NULL;
  16.     temp->data = data;
  17.     temp->next = NULL;
  18.  
  19.     head = temp;
  20.     return head;
  21. }
  22.  
  23. struct node* addAtEnd(struct node* head, int data)
  24. {
  25.     struct node *temp, *tp;
  26.     temp = malloc(sizeof(struct node));
  27.  
  28.     temp->prev = NULL;
  29.     temp->data = data;
  30.     temp->next = NULL;
  31.  
  32.     tp = head;
  33.     while (tp->next != NULL)
  34.     {
  35.         tp = tp->next;
  36.     }
  37.     tp->next = temp;
  38.     temp->prev = tp;
  39.     return head;
  40. }
  41.  
  42. struct node* reverse(struct node* head)
  43. {
  44.     struct node* ptr1 = head;
  45.     struct node* ptr2 = ptr1->next;
  46.  
  47.     ptr1->next = NULL;
  48.     ptr1->prev = ptr2;
  49.  
  50.     while (ptr2 != NULL)
  51.     {
  52.         ptr2->prev = ptr2->next;
  53.         ptr2->next = ptr1;
  54.         ptr1 = ptr2;
  55.         ptr2 = ptr2->prev;
  56.     }
  57.     head = ptr1;
  58.     return head;
  59. }
  60.  
  61. void print(struct node* head)
  62. {
  63.     struct node* ptr = head;
  64.     while (ptr != NULL)
  65.     {
  66.         printf("%d ", ptr->data);
  67.         ptr = ptr->next;
  68.     }
  69.     printf("\n");
  70. }
  71.  
  72. int main()
  73. {
  74.     struct node *head = NULL;
  75.     struct node *ptr;
  76.     head = addToEmpty(head, 24);
  77.     head = addAtEnd(head, 45);
  78.     head = addAtEnd(head, 9);
  79.    
  80.     printf("Before Reversing the list: ");
  81.     print(head);
  82.  
  83.     head = reverse(head);
  84.     printf("After Reversing the list: ");
  85.     print(head);
  86.  
  87.     return 0;
  88. }
  89.  
  90.  
  91. /*
  92. Output:
  93. Before Reversing the list : 24 45 9
  94. After Reversing the list : 9 45 24
  95. */
Add Comment
Please, Sign In to add comment