LC 206 Reverse Linked List
Question:
Reverse a singly linked list.
Approach 1 (Iterative):
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
例子:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
1 head , curr ->2->3->4->5->NULL ; prev = NULL
NULL<-1 pre ; 2 curr ->3->4->5->NULL
NULL<-1 <- 2 pre ; 3 curr->4->5->NULL
NULL<-1 <- 2 <- 3 pre ; 4 curr ->5->NULL
NULL<-1 <- 2 <- 3 <- 4 pre ; 5 curr->NULL
NULL<-1 <- 2 <- 3 <- 4 <- 5 (curr ==NULL)
Approach 2 (Recursive):
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
例子:
Input: 1->2->3-> 4->NULL
Output: 4->3->2->1->NULL
1 head -> 2 -> 3 -> 4 ->NULL
1 ->2 head ->3 -> 4 ->NULL
1 ->2 ->3 head -> 4 ->NULL
1 ->2 ->3 -> 4 head ->NULL (head .next == null )
1 ->2 ->NULL ; NULL <- 3 <- 4 (Back Track)
1 ->NULL ; NULL<-2 <- 3 <- 4 (Back Track)
NULL<- 1 <-2 <- 3 <- 4 (Back Track & Return)