码迷,mamicode.com
首页 > 其他好文 > 详细

刷题6 从尾到头打印链表

时间:2017-12-22 03:35:49      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:思路   result   null   print   col   begin   tor   color   nod   

描述:  输入一个链表,从尾到头打印链表每个节点的值。

 

最初思路:

 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(ListNode* head) {
13         vector<int> array;
14 
15         while(head != NULL) 
16         {
17             array.push_back(head->val);
18             head = head->next;
19         }
20         
21         return vector<int>(array.rbegin(), array.rend());
22     }
23 };

 

方法多了去了,比如用vector跟stack配合:

 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(ListNode* head) {
13         vector<int> result;
14         stack<int> stack;
15         while(head != NULL) 
16         {
17             stack.push(head->val);
18             head = head->next;
19         }
20         
21         while(!stack.empty())
22         {
23             result.push_back(stack.top());
24             stack.pop();
25         }
26         return result;
27     }
28 };

 

vector跟stack结合的还有用stack<ListNode*>的。

 

刷题6 从尾到头打印链表

标签:思路   result   null   print   col   begin   tor   color   nod   

原文地址:http://www.cnblogs.com/purehol/p/8083258.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!