输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
思路:先将链表值拷贝到一个新的List中,然后将新的List倒序拷贝到结果List中
(注意空值的处理,若输入为空链表,则应该返回空的List)
C#实现
using
System.Collections.Generic;
/*
public class ListNode
{
public int val;
public ListNode next;
public ListNode (int x)
{
val = x;
}
}*/
class
Solution
{
List<
int
> newList =
new
List<
int
>();
List<
int
> result =
new
List<
int
>();
// 返回从尾到头的列表值序列
public
List<
int
> printListFromTailToHead(ListNode listNode)
{
// write code here
if
(listNode ==
null
)
return
new
List<
int
>{};
else
{
newList.Add(listNode.val);
while
(listNode.next !=
null
)
{
newList.Add(listNode.next.val);
listNode=listNode.next;
}
for
(
int
i = newList.Count - 1; i >= 0; i--)
{
result.Add(newList[i]);
}
return
result;
}
}
}