经典软件面试题(2)

设链表节点为

[cpp] view plaincopy
  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为例,图示如下

经典软件面试题(2)_第1张图片

 

实现及测试代码如下:

[cpp:nogutter] view plaincopy
  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.     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.   
  38. List ReverseList(List head)  
  39. {  
  40.     if(head->next == NULL || head->next->next == NULL)    
  41.     {  
  42.        return head;   /*链表为空或只有一个元素则直接返回*/  
  43.     }  
  44.   
  45.     ListNode *t = NULL,  
  46.              *p = head->next,  
  47.              *q = head->next->next;  
  48.     while(q != NULL)  
  49.     {          
  50.       t = q->next;  
  51.       q->next = p;  
  52.       p = q;  
  53.       q = t;  
  54.     }  
  55.   
  56.     /*此时q指向原始链表最后一个元素,也是逆转后的链表的表头元素*/  
  57.     head->next->next = NULL;  /*设置链表尾*/  
  58.     head->next = p;           /*调整链表头*/  
  59.     return head;  
  60. }  
  61.   
  62. void PrintList(List head)  
  63. {  
  64.     ListNode* p = head->next;  
  65.     while(p != NULL)  
  66.     {  
  67.         printf("%d ", p->data);  
  68.         p = p->next;  
  69.     }  
  70.     printf("\n");  
  71. }  

 


你可能感兴趣的:(qq,面试,list,测试,null)