程序解析
本题要返回一个ArrayList,而且是从尾至头。这让我们想到使用堆栈Stack来解决问题。先从头至尾遍历至栈,在将数据出栈即可。
源代码
package nowcoderPractice;
import java.util.ArrayList;
import java.util.Stack;
public class testNode {
public static void main(String[] args) {
ArrayList<Integer> list1=new ArrayList<Integer>();//建立数据表
Stack<Integer> stack=new Stack<Integer>();//建立数据栈
//执行入栈操作
while(head!=null)
{
stack.push(head.val);
head=head.next;
}
//执行出栈操作
while(!stack.empty())
{
list1.add(stack.pop());
}
System.out.println(list1);
}
}
京公网安备 11010502036488号