- 输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
- 递归
- 栈
- 反转链表
以上三种方式均可
- Java 代码
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> res = new ArrayList<>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode == null) return res;
printListFromTailToHead(listNode.next);
res.add(listNode.val);
return res;
}
}
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> vec;
if(!head) return vec;
stack<int> st;
ListNode *p =head;
while(p){
st.push(p->val);
p=p->next;
}
while(!st.empty())
{
vec.push_back(st.top());
st.pop();
}
return vec;
}
};
网友评论