从尾到头打印链表

【题目描述】

输入一个链表,从尾到头打印链表每个节点的值。 
输入描述:
输入为链表的表头
输出描述:
输出为需要打印的“新链表”的表头
【代码实现】
实现一:基于栈的实现
 1 /**
 2 *  struct ListNode {
 3 *        int val;
 4 *        struct ListNode *next;
 5 *        ListNode(int x) :
 6 *              val(x), next(NULL) {
 7 *        }
 8 *  };
 9 */
10 class Solution {
11 public:
12     vector<int> printListFromTailToHead(struct ListNode* head) {
13         stack <struct ListNode*> nodes;
14         struct ListNode* pNode=head;
15         vector <int> vec;
16         while(pNode!=NULL)
17         {
18             nodes.push(pNode);
19             pNode=pNode->next;
20         }
21 
22         while(!nodes.empty())
23         {
24             vec.push_back(nodes.top()->val);
25             nodes.pop();
26         }           
27         return vec;
28     }
29 };

 实现二:利用vector的插入函数

 1 /**
 2 *  struct ListNode {
 3 *        int val;
 4 *        struct ListNode *next;
 5 *        ListNode(int x) :
 6 *              val(x), next(NULL) {
 7 *        }
 8 *  };
 9 */
10 class Solution {
11 public:
12     vector<int> printListFromTailToHead(struct ListNode* head) {
13         struct ListNode* pNode=head;
14         vector <int> vec;
15        while(pNode!=NULL)
16        {
17            vec.insert(vec.begin(),pNode->val);
18            pNode=pNode->next;
19        }
20         return vec;
21     }
22 };
【点评】

    头插vector 效率太低,可以考虑替代方案:先vector.push_back 返回之前翻转vector,std::reverse(begin,end)。

实现三:利用vector的反转函数

 1 /**
 2 *  struct ListNode {
 3 *        int val;
 4 *        struct ListNode *next;
 5 *        ListNode(int x) :
 6 *              val(x), next(NULL) {
 7 *        }
 8 *  };
 9 */
10 class Solution {
11 public:
12     vector<int> printListFromTailToHead(struct ListNode* head) {
13        struct ListNode* pNode=head;
14        vector <int> vec;
15        while(pNode!=NULL)
16        {
17            vec.push_back(pNode->val);
18            pNode=pNode->next;
19        }  
20        reverse(vec.begin(),vec.end());
21        return vec;
22     }
23 };

 

转载于:https://www.cnblogs.com/lou424/p/5023845.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值