链表逆序

来源:互联网 发布:串行12864接单片机 编辑:程序博客网 时间:2024/05/02 03:08

设链表节点为

[cpp] view plaincopyprint?
  1. typedef struct tagListNode{ 
  2.     int data; 
  3.     struct tagListNode* next; 
  4. }ListNode, *List; 

要求将一带链表头List head的单向链表逆序。

分析:

  1). 若链表为空或只有一个元素,则直接返回;

  2). 设置两个前后相邻的指针p,q. 将p所指向的节点作为q指向节点的后继;

  3). 重复2),直到q为空

  4). 调整链表头和链表尾

示例:以逆序A->B->C->D为例,图示如下

实现及测试代码如下:

[cpp] view plaincopyprint?
  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.     ListNode *head; 
  15.     head = (ListNode*)malloc(sizeof(ListNode)); 
  16.     head->next = NULL; 
  17.     head->data = -1; 
  18.  
  19.     //将[1,10]加入链表 
  20.     int i; 
  21.     ListNode *p, *q; 
  22.     p = head; 
  23.     for(int i = 1; i <= 10; i++) 
  24.     { 
  25.         q = (ListNode *)malloc(sizeof(ListNode)); 
  26.         q->data = i; 
  27.         q->next = NULL; 
  28.         p->next = q; 
  29.         p = q;         
  30.     } 
  31.  
  32.     PrintList(head);           /*输出原始链表*/ 
  33.     head = ReverseList(head);  /*逆序链表*/ 
  34.     PrintList(head);           /*输出逆序后的链表*/ 
  35.     return 0; 
  36.  
  37. List ReverseList(List head) 
  38.     if(head->next == NULL || head->next->next == NULL)   
  39.     { 
  40.        return head;   /*链表为空或只有一个元素则直接返回*/ 
  41.     } 
  42.  
  43.     ListNode *t = NULL, 
  44.              *p = head->next, 
  45.              *q = head->next->next; 
  46.     while(q != NULL) 
  47.     {         
  48.       t = q->next; 
  49.       q->next = p; 
  50.       p = q; 
  51.       q = t; 
  52.     } 
  53.  
  54.     /*此时q指向原始链表最后一个元素,也是逆转后的链表的表头元素*/ 
  55.     head->next->next = NULL;  /*设置链表尾*/ 
  56.     head->next = p;           /*调整链表头*/ 
  57.     return head; 
  58.  
  59. void PrintList(List head) 
  60.     ListNode* p = head->next; 
  61.     while(p != NULL) 
  62.     { 
  63.         printf("%d ", p->data); 
  64.         p = p->next; 
  65.     } 
  66.     printf("/n");