Q:輸入一個鏈表,從尾到頭打印鏈表每個節點的值。
兩種實現方式:
public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> stack=new Stack<Integer>();
ArrayList<Integer> list = new ArrayList<Integer>();
while(listNode!=null){
stack.push(listNode.val);
listNode=listNode.next;
}
while(!stack.isEmpty()){list.add(stack.pop());}
return list;
}
public static void printReverseListRecursive2(ListNode root){
if(root!=null){
if(root.next!=null){
printReverseListRecursive2(root.next);
}
System.out.print(root.val+" ");
}
}