Back to Blog

Reverse Linked List

#null#list#Test#QQ

Define the linked list node as:

[cpp]  view plain copy

  1. typedef struct tagListNode{  
  2.     int data;  
  3.     struct tagListNode* next;  
  4. }ListNode, *List;  

The requirement is to reverse a singly linked list with a head node List head.

Analysis:

  1). If the linked list is empty or contains only one element, return directly;

  2). Set up two adjacent pointers, p and q. The node pointed to by p will become the successor of the node pointed to by q;

  3). Repeat step 2) until q is null.

  4). Adjust the head and tail of the linked list.

Example: Taking A->B->C->D as an example for reversal, the diagram is as follows:

The implementation and test code are as follows:

[cpp:nogutter]  view plain copy

  1. #include <stdio.h>  

  2. #include <stdlib.h>  

  3. typedef struct tagListNode{  

  4.     int data;  

  5.     struct tagListNode* next;  

  6. }ListNode, *List;  

  7. void PrintList(List head);  

  8. List ReverseList(List head);  

  9. int main()  

  10. {  

  11.     //Allocate head node for the linked list  

  12.     ListNode *head;  

  13.     head = (ListNode*)malloc(sizeof(ListNode));  

  14.     head->next = NULL;  

  15.     head->data = -1;  

  16.     //Add [1,10] to the linked list  

  17.     int i;  

  18.     ListNode *p, *q;  

  19.     p = head;  

  20.     for(int i = 1; i <= 10; i++)  

  21.     {  

  22.         q = (ListNode *)malloc(sizeof(ListNode));  

  23.         q->data = i;  

  24.         q->next = NULL;  

  25.         p->next = q;  

  26.         p = q;          

  27.     }  

  28.     PrintList(head);           /* Output original linked list */  

  29.     head = ReverseList(head);  /* Reverse linked list */  

  30.     PrintList(head);           /* Output reversed linked list */  

  31.     return 0;  

  32. }  

  33. List ReverseList(List head)  

  34. {  

  35.     if(head->next == NULL || head->next->next == NULL)    

  36.     {  

  37.        return head;   /* If the linked list is empty or has only one element, return directly */  

  38.     }  

  39.     ListNode *t = NULL,  

  40.              *p = head->next,  

  41.              *q = head->next->next;  

  42.     while(q != NULL)  

  43.     {          

  44.       t = q->next;  

  45.       q->next = p;  

  46.       p = q;  

  47.       q = t;  

  48.     }  

  49.     /* At this point, q points to the last element of the original list, which is also the head element of the reversed list */  

  50.     head->next->next = NULL;  /* Set the linked list tail */  

  51.     head->next = p;           /* Adjust the linked list head */  

  52.     return head;  

  53. }  

  54. void PrintList(List head)  

  55. {  

  56.     ListNode* p = head->next;  

  57.     while(p != NULL)  

  58.     {  

  59.         printf("%d ", p->data);  

  60.         p = p->next;  

  61.     }  

  62.     printf("/n");  

  63. }