【剑指offer】从尾到头打印链表 python/C++

454 阅读1分钟

【题目描述】

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

【思路】

借助栈实现。

【代码】

C++:
//stack数据类型,有push,pop,top等方法。
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        stack<int> STACK;
        while(head!=NULL){
            STACK.push(head->val);
            head=head->next;
        }
        vector<int> re;
        while(!STACK.empty()){
            re.push_back(STACK.top());
            STACK.pop();
        }
        return re;
        
    }
};
python:
class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        stack=[]
        re=[]
        while(listNode):
            stack.append(listNode.val)
            listNode=listNode.next
        while stack:
            re.append(stack.pop())
        return re