您的位置:首页 > Web前端

《剑指Offer》题目——从尾到头打印链表

2017-06-04 21:28 357 查看
题目描述:输入一个链表,从尾到头打印链表每个节点的值。

题目分析:用栈;Java用Stack不如用Deque接口,原因可以见链接:http://stackoverflow.com/questions/12524826/why-should-i-use-deque-over-stack

public class ReverseList {
class ListNode{
int val;
ListNode next = null;

ListNode(int val){
this.val = val;
}
}
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> stack = new Stack<Integer>();
ArrayList<Integer> list = new ArrayList<Integer>();

//注意这里while循环结束的条件是listNode不为空,而不是listNode.next不为空
while (listNode!=null){
stack.push(listNode.val);
listNode = listNode.next;
}
while (!stack.empty()){
list.add(stack.pop());
}
return list;
}
public static void main(String[] args){

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: