本质是一个反转单链表
题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
解法1:链表逆置
最直接想到的就是用三个指针逆置链表,然后打印(数组尾插)
注意:函数返回值是一个数组,所以最终要输出一个数组
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> ret;
if (head == NULL) return ret;
ListNode* pre = NULL;
ListNode* cur = head->next;
while (cur)//逆置
{
head->next = pre;
pre = head;
head = cur;
cur = cur->next;
}
head->next = pre;
while (head)//打印
{
ret.push_back(head->val);
head = head->next;
}
return ret;
}
};
解法2:出入栈
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
stack<int> s;
vector<int> v;
//让节点的值入栈
while(head)
{
s.push(head->val);
head=head->next;
}
//出栈
while(!s.empty())
{
v.push_back(s.top());
s.pop();
}
return v;
}
};
解法3:递归
void printListFromTailToHead(ListNode* head)
{
if (head == NULL) return;
if (head->next)
printListFromTailToHead(head->next);
printf("%d ", head->val);
}
解法4:应用vector中的反向迭代器
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> v;
while(head)
{
v.push_back(head->val);
head=head->next;
}
return vector<int>(v.rbegin(),v.rend());
}
};