问题描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
解析
看到这问题,第一反应是递归调用,但是递归如果太深入就会产生栈溢出。所以更改成java里面有个栈的数据结构类型——Stack。
代码
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Stack;
public class Main{
public static void main(String[] args) {
ListNode listNode=new ListNode(10);
ListNode node=listNode;
for(int i=0;i<10;i++)
{
node.next=new ListNode((int)(Math.random()*100));
node=node.next;
}
node=listNode;
while(node!=null)
{
System.out.print(node.val+" ");
node=node.next;
}
System.out.println();
ArrayList arrayList= printListFromTailToHead(listNode);
Iterator iterator=arrayList.iterator();
while(iterator.hasNext())
{
System.out.print(iterator.next()+" ");
}
}
public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack stack = new Stack();
ListNode node = listNode;
ArrayList<Integer> newList = new ArrayList<Integer>();
while (node.next != null) {
stack.push(node.val);
node = node.next;
}
while (!stack.empty()) {
newList.add((Integer) stack.pop());
}
return newList;
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}