zoukankan      html  css  js  c++  java
  • 逆向遍历链表

     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
    ",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
    ",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("逆向遍历
    ");
    59      head = head->next;//逆向遍历注意点:头结点的数据域为空,所以要提前跳过头结点。不然递归逐级返回会打印头结点的数据域。
    60      RtraverList(head);
    61      return 0;
    62  }
  • 相关阅读:
    c# 不常用逻辑运算符
    c# 简单日志记录类 log

    最短路径
    A+B
    floyd 算法
    Kruskal 算法
    快排
    顺序表的逆排
    顺序表中多余元素的删除
  • 原文地址:https://www.cnblogs.com/wangchaomahan/p/9734702.html
Copyright © 2011-2022 走看看