从尾到头打印链表

题目描述

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

C++

1
2
3
4
5
6
7
8
9
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/

Java

1
2
3
4
5
6
7
8
9
10
11
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/

解题思路

新建一个栈,利用栈的先进后出的特性,从头到尾遍历链表依次放到栈里,最后再从栈中一个个弹出来。

代码实现

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> value;
stack<int> stk;
ListNode *p = head;
while (p != NULL) {
stk.push(p->val);
p = p->next;
}
while (!stk.empty()) {
value.push_back(stk.top());
stk.pop();
}
return value;
}
};

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> stk = new Stack<Integer>();
ArrayList<Integer> tmp = new ArrayList();
while (listNode != null) {
stk.push(listNode.val);
listNode = listNode.next;
}
while (!stk.empty()){
tmp.add(stk.pop());
}
return tmp;
}
}