从尾到头打印链表

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

python:

 1 # -*- coding:utf-8 -*-
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     def printListFromTailToHead(self, listNode):
 9         lst , back_lst = [],[]
10         while not listNode:
11             return lst
12         while listNode:
13             lst.append(listNode.val)
14             listNode = listNode.next
15         while lst:
16             back_lst.append(lst.pop())
17         return back_lst

思想:

先入栈,进入lst(lst是入栈的列表)

然后再出栈,lst.pop,得到的就是反转链表。back_lst是出栈的列表。

 

c++

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

 

posted @ 2019-05-28 17:47  Austin_anheqiao  阅读(112)  评论(0编辑  收藏  举报