leetcodeOffer06:从尾到头打印链表(堆栈)

把这个题当翻转链表做可以,然后就贼烂。
leetcodeOffer06:从尾到头打印链表(堆栈)_第1张图片

class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> res;
        ListNode* copy = head;
        if(head == NULL)return res;
        while(copy -> next)
        {
            copy = copy -> next;
        }
        while(copy != head)
        {
            ListNode* fore = head;
            while(fore -> next != copy)
            {
                fore =fore -> next;
            }
            res.push_back(copy->val);
            copy = fore;//不同就在于它少了一步把整个连起来的过程,简化了翻转链表的过程

        }
        res.push_back(head->val);
        return res;

    }
};

实际上,后进先出的是堆栈。

class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> res;
        ListNode* copy = head;
        stack<int> zhan;
        while(copy)
        {
            zhan.push(copy -> val);
            copy = copy -> next;
        }
        while(!zhan.empty())
        {
            res.push_back(zhan.top());
            zhan.pop();

        }
        return res;
    }

};

leetcodeOffer06:从尾到头打印链表(堆栈)_第2张图片

你可能感兴趣的:(leetcode)