逆向遍历链表

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 /*
 4 从尾到头打印链表。
 5 思路:利用递归调用逐级返回的特性,也就是栈的特性:先进后出,后进先出。
 6 */
 7 typedef struct node
 8  {
 9      int data;
10       struct node * next;
11  }NODE;
12  NODE * createList()
13 {
14      NODE * head = (NODE *)malloc(sizeof(NODE));
15      head->next = NULL;
16  
17      return head;
18  }
19  void insertNode(NODE *head,int insertData)
20  {
21      NODE * sur = (NODE *)malloc(sizeof(NODE));
22      sur->data = insertData;
23 
24      sur->next = head->next;
25      head->next = sur;
26  
27  }
28  void traverList(NODE *head)
29  {
30      int i = 1;
31      head = head->next;
32      while(head)
33      {
34          printf("第%d结点 = %d\n",i,head->data);
35         head = head->next;
36          i++;
37     }
38  }
39  //逆向遍历
40  void RtraverList(NODE *head)
41  {
42      if(head == NULL)
43          return ;
44      else
45      {
46          RtraverList(head->next);
47          printf("%d\n",head->data);
48      }
49  }
50 
51  
52  int main(void)
53  {
54      NODE *head = createList();
55      for(int i = 0;i<5;i++)
56          insertNode(head,rand()%100);
57      traverList(head);
58      printf("逆向遍历\n");
59      head = head->next;//逆向遍历注意点:头结点的数据域为空,所以要提前跳过头结点。不然递归逐级返回会打印头结点的数据域。
60      RtraverList(head);
61      return 0;
62  }

 

posted on 2018-10-01 15:03  王朝马汉  阅读(873)  评论(0编辑  收藏  举报

导航