Please enable Javascript to view the contents

剑指office(三)从尾到头打印链表

 ·  ☕ 1 分钟  ·  🎅 YSL

题目描述

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

示例1

输入

{67,0,24,58}

返回值

[58,24,0,67]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        stack<int> temp;
        while(head!=NULL)
        {
            temp.push(head->val);
            head = head->next;
        }
        vector<int> result;
        int tempS = temp.size();
        for(int i = 0;i<tempS;i++)
        {
            result.push_back(temp.top());
            temp.pop();
        }
        return result;
    }
};