您的位置:首页 > 职场人生

剑指offer面试题6-从尾到头打印链表-java

2017-06-07 14:46 621 查看
输入一个链表,从尾到头打印链表每个节点的值

class ListNode{
int val;
ListNode next = null;
public ListNode(int val){
this.val = val;
}
}
public class printListReverse {
//从尾到头打印链表
public static ArrayList<Integer> printListReverse(ListNode listNode){
if (listNode==null)return null;
Stack<Integer> stack = new Stack<Integer>();
while (listNode!=null){
stack.push(listNode.val);
listNode=listNode.next;
}
ArrayList<Integer> arrayList = new ArrayList<Integer>();
while(!stack.isEmpty()){
arrayList.add(stack.pop());
}
return arrayList;
}

public static void main(String[] args){
ListNode a = new ListNode(1);
ListNode b = new ListNode(2);
ListNode c = new ListNode(3);
a.next=b;
b.next=c;
ArrayList<Integer> list = printListReverse(a);
for (int i=0;i<list.size();i++) {
System.out.print(list.get(i) + " ");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: