<算法编程> 从尾到头打印链表

  1 #include<iostream>
  2 using namespace std;
  3 
  4 struct Node
  5 {
  6     int n;
  7     Node* pNext;
  8 };
  9 
 10 Node* AddNode(Node** pHead,Node* pNode)
 11 {
 12     if((*pHead) == NULL)
 13     {
 14         (*pHead) = pNode;
 15     }
 16     else 
 17     {
 18         Node* pEnd = (*pHead);
 19         while(pEnd->pNext != NULL)
 20         {
 21             pEnd = pEnd->pNext;
 22         }
 23         pEnd->pNext = pNode;
 24     }
 25 
 26     return *pHead;
 27 }
 28 
 29 void PrintList(Node* pHead)
 30 {
 31     while(pHead)
 32     {
 33         cout << pHead->n << " ";
 34         pHead = pHead->pNext;
 35     }
 36     cout << endl;
 37 }
 38 
 39 //递归方式
 40 void pfun(Node* pHead)
 41 {
 42     if(pHead == NULL) return ;
 43     
 44     Node* pNode = pHead;
 45     if(pNode != NULL)
 46     {
 47         if(pNode->pNext != NULL)
 48             pfun(pNode->pNext);
 49         cout << pNode->n << endl;
 50     }
 51 
 52     return ;
 53 }
 54 
 55 //数组方式:开辟一个和链表一样长度的数组 遍历一遍链表存进数组
 56 //然后数组倒着输出就可以了
 57 
 58 //栈:利用栈先进后出的方式来打印
 59 //遍历一个链表就压一个进栈
 60 //最后全部弹出打印
 61 
 62 int main()
 63 {
 64     Node* pHead = NULL;
 65 
 66     Node* pNode1 = new Node;
 67     pNode1->n = 1;
 68     pNode1->pNext = NULL;
 69     AddNode(&pHead,pNode1);
 70     Node* pNode2 = new Node;
 71     pNode2->n = 2;
 72     pNode2->pNext = NULL;
 73     AddNode(&pHead,pNode2);
 74     Node* pNode3 = new Node;
 75     pNode3->n = 3;
 76     pNode3->pNext = NULL;
 77     AddNode(&pHead,pNode3);
 78     Node* pNode4 = new Node;
 79     pNode4->n = 4;
 80     pNode4->pNext = NULL;
 81     AddNode(&pHead,pNode4);
 82     Node* pNode5 = new Node;
 83     pNode5->n = 5;
 84     pNode5->pNext = NULL;
 85     AddNode(&pHead,pNode5);
 86     Node* pNode6 = new Node;
 87     pNode6->n = 6;
 88     pNode6->pNext = NULL;
 89     AddNode(&pHead,pNode6);
 90     Node* pNode7 = new Node;
 91     pNode7->n = 7;
 92     pNode7->pNext = NULL;
 93     AddNode(&pHead,pNode7);
 94     Node* pNode8 = new Node;
 95     pNode8->n = 8;
 96     pNode8->pNext = NULL;
 97     AddNode(&pHead,pNode8);
 98     
 99     pfun(pHead);
100 
101     system("pause");
102     return 0;
103 }

 

转载于:https://www.cnblogs.com/Aaaaaalei0612/p/11218800.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值