每天一个小算法(3)----倒序打印链表

这个比较简单,用栈、递归、倒转链表都可以实现,不再过多解释。

代码使用递归实现

 1 #include <stdio.h>
 2 #include <time.h>
 3 #include <stdlib.h>
 4 typedef struct Node
 5 {
 6     int data;
 7     Node* next;
 8 }Node, *List;
 9 
10 
11 List createList(int num) //随机生成数字,构造链表
12 {
13     List aList = (List)malloc(sizeof(Node));
14     aList->next = NULL;
15     aList->data = 0;
16     Node* qT = aList;
17 
18      // srand((int)time(0));
19      for ( int i=0; i< num; ++i)
20      {
21          Node* pTN = (Node*)malloc(sizeof(Node));
22          pTN->data = rand()%100;
23          pTN->next = NULL;
24          qT->next = pTN;
25          qT = pTN;
26      }
27      return aList;
28 }
29 
30 void printList(List aList)    //正序打印链表
31 {
32     if ( aList == NULL || aList->next == NULL )
33         return;
34 
35     Node* pT = aList->next;
36     printf("element of the list:\n\t");
37     while( pT != NULL )
38     {
39         printf("%d ", pT->data);
40         pT = pT->next;
41     }
42 
43     printf("\n");
44 }
45 
46 void reversePrintList(List aList)    //倒序打印链表
47 {
48     if ( aList == NULL )
49         return;
50 
51     reversePrintList(aList->next);
52     printf("%d ", aList->data);
53 }
54 
55 void deleteList(List aList)    //删除链表
56 {}
57 
58 int main(int argc, char const *argv[])
59 {
60      srand((int)time(0));
61     List aList = createList(7);
62     printList(aList);
63     printf("reverse print the list:\n\t");
64     reversePrintList(aList->next);
65     printf("\n");
66 
67     deleteList(aList);
68     
69     return 0;
70 }

 

转载于:https://www.cnblogs.com/yrpen/p/3783703.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值