牛客网刷题(一) 从尾到头打印链表

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

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        stack<int> stack;
        vector<int> vector;
         
        struct ListNode *p=head;
        if(head!=NULL)             //如果head不为空
        {
            stack.push(head->val);     //那么先将head的值输入到stack中
            while((p=p->next)!=NULL)   //判断head的下一个节点是否为空
            {
               stack.push(p->val);     //不为空时,将p的val的值输入到stack中
            }

            while(!stack.empty())      //如果stack不为空时,将倒序的链表值保存到vector中
            {
                vector.push_back(stack.top());
                stack.pop();          //出栈
            }
        }
            return vector;
     }
};

猜你喜欢

转载自blog.csdn.net/weixin_42736024/article/details/83029535