牛客66题(3)从尾到头打印链表

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

思路:很简单,设置一个栈,遍历链表将链表依次压栈,最后依次弹出。

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int>v;
        if(head==NULL)
            return v;
        stack<int>s;
        ListNode* temp=head;
      
        while(temp!=NULL)
        {
            s.push(temp->val);
            temp=temp->next;
        }
        while(!s.empty())
        {
            v.push_back(s.top());
            s.pop();
        }
        return v;
    }
};

总结:很简单,就不说了,估计笔试也不会考这么简单的题了

猜你喜欢

转载自blog.csdn.net/libinxxx/article/details/84380701