题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
解题思路:
第一种方法是直接使用vector 的reverse 方法 将链表从头到尾push_back到vector中 再反转 返回。
第二种方法是 使用一个栈,将链表从头到尾push到栈中,再依次出栈,将出栈的元素push_back到vector 中 返回 。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
#include <algorithm> // std::reverse
#include <vector>
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> myvector;
if(head==NULL)
return myvector;
ListNode *p=head;
while(p!=NULL)
{
myvector.push_back(p->val);
p=p->next;
}
std::reverse(myvector.begin(),myvector.end());
return myvector;
/*
vector<int> myvector;
stack<int> s;
ListNode *p=head;
while(p!=NULL)
{
s.push(p->val);
p=p->next;
}
while(!s.empty())
{
myvector.push_back(s.top());
s.pop();
}
return myvector;
*/
}
};
go 版本:
func printListFromTailToHead( head *ListNode ) []int {
if head == nil{
return []int{}
}
var val []int
for ;head != nil;head = head.Next{
val = append(val,head.Val)
}
var res []int
for index:= len(val)-1;index >= 0;index --{
res = append(res,val[index])
}
return res
}