题目描述:
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
解题思路:
递归方法:如链表1->2->3->4,先递归考虑链表2->3->4,然后在返回结果中添加1;一层层递归下去,当链表为null时,直接返回空的容器。
栈方法:遍历一遍链表,将数值压入栈中;然后将栈中的所有元素弹出,并添加到ArrayList容器中。
代码如下:
C++版本
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
//递归实现
class Solution {
public:
void printListFromTailToHeadCore(ListNode *head, vector<int> &res)
{
if(!head)
return;
else if(!head->next)
{
res.push_back(head->val);
return;
}
printListFromTailToHeadCore(head->next, res);
res.push_back(head->val);
return;
}
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
if(!head)
return res;
printListFromTailToHeadCore(head, res);
return res;
}
};
//栈实现
class Solution
{
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector <int> res;
stack<int> sta;
while(head != NULL)
{
sta.push(head->val);
head = head->next;
}
while(!sta.empty())
{
res.push_back(sta.top());
sta.pop();
}
return res;
}
};
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> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> res = new ArrayList<Integer>();
printListFromTailToHeadCore(listNode, res);
return res;
}
public void printListFromTailToHeadCore(ListNode listNode, ArrayList<Integer> res)
{
if(listNode == null)
return;
printListFromTailToHeadCore(listNode.next, res);
res.add(listNode.val);
return;
}
}
//栈实现
import java.util.ArrayList;
import java.util.Stack;
public class Solution{
public ArrayList<Integer> printListFromTailToHead(ListNode listNode)
{
ArrayList<Integer> res = new ArrayList<>();
Stack<Integer> sta = new Stack<>();
while(listNode != null)
{
sta.push(listNode.val);
listNode = listNode.next;
}
while(!sta.isEmpty())
{
res.add(sta.pop());
}
return res;
}
}