题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
题目分析:从尾到头其实就是链表的反转,链表常见的反转方法有两种,1、头插法反转;2、原地反转。本题还可以借助栈的前进后出特性实现链表的反转输出,先遍历一次链表将结果存入栈中,然后从栈中依次取出栈顶元素压入数组(vector)中。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> result;
stack<int> stk;
ListNode *p = head;
while(p != NULL)
{
stk.push(p->val);
p=p->next;
}
int length = stk.size();
for(int i=0;i<length;i++)
{
result.push_back(stk.top());
stk.pop();
}
return result;
}
};
另外一种解法,利用头插法(vector的insert()方法),每次取下链表中一个节点,将其值存入数组的头部,代码如下:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> result;
if(head != NULL)
{
result.insert(result.begin(),head->val);
while(head->next != NULL)
{
result.insert(result.begin(),head->next->val);
head=head->next;
}
}
return result;
}
};