Print Linked List Recursively Reversely
注意:可以不翻转链表,反着打印就行。
Solution 1: Iterative O(n); O(1)
先翻转,再打印
public void printList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next; //cur.next can be null when cur is the last node
cur.next = pre;
pre = cur;
cur = next;
}
ListNode newHead = pre;
while (newHead != null) {
// if (newHead.next == null) {
// System.out.print(newHead.val);
// break;
// }
// System.out.print(newHead.val + "->");
System.out.print(newHead.val + " ");
newHead = newHead.next;
}
}
Solution 2: Iterative, stack O(n); O(n)
public void printList(ListNode head){
Stack<ListNode> stack = new Stack<>();
while (head != null) {
stack.push(head);
head = head.next;
}
while (!stack.isEmpty())
System.out.println(stack.pop().val);
}
Solution 3: Recursive O(n); O(n)
public void printList(ListNode head) {
if (head == null) return;
printList(head.next);
System.out.print(head.val + " ");
}