题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
题目分析
链表反转一般有三种方法:1、递归;2、栈;3、节点替换。
下面介绍前两种方法,第三种方法后面还有一道链表反转的题,在那详细介绍。
1、递归
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
/*利用递归方法实现*/
vector<int> ArrayList;
printListFromTailToHead(ArrayList,head);
return ArrayList;
}
void printListFromTailToHead(vector<int> &ArrayList,ListNode* head)
{
if(head != NULL)
{
if(head -> next != NULL)
{
printListFromTailToHead(ArrayList,head -> next);
}
ArrayList.push_back(head->val);
}
}
};
2、栈
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
//利用栈方法实现
vector<int> ArrayList;
stack<int> sta;
ListNode *p = head;
while(p != NULL)
{
sta.push(p -> val);
p = p ->next;
}
int va ;
while(!sta.empty())
{
ArrayList.push_back(sta.top());
sta.pop();
}
return ArrayList;
}
};