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

xiaoxiao2021-02-28  81

输入一个链表,从尾到头打印链表每个节点的值

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) + " "); } } }

转载请注明原文地址: https://www.6miu.com/read-44193.html

最新回复(0)