【轉】單鏈表逆序

  單鏈表逆序

http://blog.csdn.net/niuer09/article/details/5961004測試


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

 

要求將一帶鏈表頭List head的單向鏈表逆序。spa

分析:.net

  1). 若鏈表爲空或只有一個元素,則直接返回;指針

  2). 設置兩個先後相鄰的指針p,q. 將p所指向的節點做爲q指向節點的後繼;blog

  3). 重複2),直到q爲空ip

  4). 調整鏈表頭和鏈表尾get

示例:以逆序A->B->C->D爲例,圖示以下string

 

實現及測試代碼以下:it

 

[cpp]  view plain copy
 
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3.   
  4. typedef struct tagListNode{  
  5.     int data;  
  6.     struct tagListNode* next;  
  7. }ListNode, *List;  
  8.   
  9. void PrintList(List head);  
  10. List ReverseList(List head);  
  11.   
  12. int main()  
  13. {  
  14.     //分配鏈表頭結點  
  15.     ListNode *head;  
  16.     head = (ListNode*)malloc(sizeof(ListNode));  
  17.     head->next = NULL;  
  18.     head->data = -1;  
  19.   
  20.     //將[1,10]加入鏈表  
  21.     int i;  
  22.     ListNode *p, *q;  
  23.     p = head;  
  24.     for(int i = 1; i <= 10; i++)  
  25.     {  
  26.         q = (ListNode *)malloc(sizeof(ListNode));  
  27.         q->data = i;  
  28.         q->next = NULL;  
  29.         p->next = q;  
  30.         p = q;          
  31.     }  
  32.   
  33.     PrintList(head);           /*輸出原始鏈表*/  
  34.     head = ReverseList(head);  /*逆序鏈表*/  
  35.     PrintList(head);           /*輸出逆序後的鏈表*/  
  36.     return 0;  
  37. }  
  38.   
  39. List ReverseList(List head)  
  40. {  
  41.     if(head->next == NULL || head->next->next == NULL)    
  42.     {  
  43.        return head;   /*鏈表爲空或只有一個元素則直接返回*/  
  44.     }  
  45.   
  46.     ListNode *t = NULL,  
  47.              *p = head->next,  
  48.              *q = head->next->next;  
  49.     while(q != NULL)  
  50.     {          
  51.       t = q->next;  
  52.       q->next = p;  
  53.       p = q;  
  54.       q = t;  
  55.     }  
  56.   
  57.     /*此時q指向原始鏈表最後一個元素,也是逆轉後的鏈表的表頭元素*/  
  58.     head->next->next = NULL;  /*設置鏈表尾*/  
  59.     head->next = p;           /*調整鏈表頭*/  
  60.     return head;  
  61. }  
  62.   
  63. void PrintList(List head)  
  64. {  
  65.     ListNode* p = head->next;  
  66.     while(p != NULL)  
  67.     {  
  68.         printf("%d ", p->data);  
  69.         p = p->next;  
  70.     }  
  71.     printf("/n");  
  72. }  
相關文章
相關標籤/搜索