剑指Offer——从尾到头打印链表

题目描述:

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

 

分析:

方法1:利用栈的性质,先从头到尾遍历链表每个节点的值存入栈中,最后一个一个出栈顺序便是从尾到头的。

方法2:直接从头到尾遍历链表存储节点的值将值存到数组中,最后翻转数组。

方法3:直接从头到尾遍历链表存储节点的值将值插入到数组的第一个位置。

方法4:递归,返回链表下一节点往下遍历的结果加上当前节点的值组成的结果。

 

方法1代码:

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

递归解法:

 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> res;
13     vector<int> printListFromTailToHead(ListNode* head) {
14         if(head) {
15             res = printListFromTailToHead(head->next);
16             res.push_back(head->val);
17             return res;
18         }
19         return res;
20     }
21 };

 

posted @ 2017-10-26 17:05  叶建成  阅读(205)  评论(0编辑  收藏  举报