fork download
  1. /* Program to reverse a doubly linked list */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. /* a node of the doubly linked list */
  6. struct node
  7. {
  8. int data;
  9. struct node *next;
  10. struct node *prev;
  11. };
  12.  
  13. /* Function to reverse a Doubly Linked List */
  14. void reverse(struct node **head_ref)
  15. {
  16. struct node *temp = NULL;
  17. struct node *current = *head_ref;
  18.  
  19. /* swap next and prev for all nodes of
  20.   doubly linked list */
  21. while (current != NULL)
  22. {
  23. temp = current->prev;
  24. current->prev = current->next;
  25. current->next = temp;
  26. current = current->prev;
  27. }
  28.  
  29. /* Before changing head, check for the cases like empty
  30.   list and list with only one node */
  31. if(temp != NULL )
  32. *head_ref = temp->prev;
  33. }
  34.  
  35.  
  36.  
  37. /* UTILITY FUNCTIONS */
  38. /* Function to insert a node at the beginging of the Doubly Linked List */
  39. void push(struct node** head_ref, int new_data)
  40. {
  41. /* allocate node */
  42. struct node* new_node =
  43. (struct node*) malloc(sizeof(struct node));
  44.  
  45. /* put in the data */
  46. new_node->data = new_data;
  47.  
  48. /* since we are adding at the begining,
  49.   prev is always NULL */
  50. new_node->prev = NULL;
  51.  
  52. /* link the old list off the new node */
  53. new_node->next = (*head_ref);
  54.  
  55. /* change prev of head node to new node */
  56. if((*head_ref) != NULL)
  57. (*head_ref)->prev = new_node ;
  58.  
  59. /* move the head to point to the new node */
  60. (*head_ref) = new_node;
  61. }
  62.  
  63. /* Function to print nodes in a given doubly linked list
  64.   This function is same as printList() of singly linked lsit */
  65. void printList(struct node *node)
  66. {
  67. while(node!=NULL)
  68. {
  69. printf("%d ", node->data);
  70. node = node->next;
  71. }
  72. }
  73.  
  74. /* Drier program to test above functions*/
  75. int main()
  76. {
  77. /* Start with the empty list */
  78. struct node* head = NULL;
  79.  
  80. /* Let us create a sorted linked list to test the functions
  81.   Created linked list will be 10->8->4->2 */
  82. push(&head, 2);
  83. push(&head, 4);
  84. push(&head, 8);
  85. push(&head, 10);
  86.  
  87. printf("\n Original Linked list ");
  88. printList(head);
  89.  
  90. /* Reverse doubly linked list */
  91. reverse(&head);
  92.  
  93. printf("\n Reversed Linked list ");
  94. printList(head);
  95.  
  96. getchar();
  97. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
 Original Linked list 10 8 4 2 
 Reversed Linked list 2 4 8 10