206. Reverse Linked List
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
题意:逆置一个单链表。
提示:您能否使用迭代和递归两种方法?
/*
这个题我们可以利用三个指针:
NULL 1 -> 2 -> 3 -> 4 -> 5
↑ ↑↑
a bc
(1)c = b->next; (2)b->next = a; (3)a = b; (4)b = c;
NULL 1 -> 2 -> 3 -> 4 -> 5 NULL <- 1 2 -> 3 -> 4 -> 5 NULL <- 1 2 -> 3 -> 4 -> 5 NULL <- 1 2 -> 3 -> 4 -> 5
↑ ↑ ↑ ↑ ↑ ↑ ↑↑ ↑ ↑ ↑↑
a b c a b c ab c a bc
(1)c = b->next; (2)b->next = a; (3)a = b; (4)b = c;
NULL <- 1 2 -> 3 -> 4 -> 5 NULL <- 1 <- 2 3 -> 4 -> 5 NULL <- 1 <- 2 3 -> 4 -> 5 NULL <- 1 <- 2 3 -> 4 -> 5
↑ ↑ ↑ ↑ ↑ ↑ ↑↑ ↑ ↑ ↑↑
a b c a b c ab c a bc
(1)c = b->next; (2)b->next = a; (3)a = b; (4)b = c;
NULL <- 1 <- 2 3 -> 4 -> 5 NULL <- 1 <- 2 <- 3 4 -> 5 NULL <- 1 <- 2 <- 3 4 -> 5 NULL <- 1 <- 2 <- 3 4 -> 5
↑ ↑ ↑ ↑ ↑ ↑ ↑↑ ↑ ↑ ↑↑
a b c a b c ab c a bc
(1)c = b->next; (2)b->next = a; (3)a = b; (4)b = c;
NULL <- 1 <- 2 <- 3 4 -> 5 NULL <- 1 <- 2 <- 3 <- 4 5 NULL <- 1 <- 2 <- 3 <- 4 5 NULL <- 1 <- 2 <- 3 <- 4 5
↑ ↑ ↑ ↑ ↑ ↑ ↑↑ ↑ ↑ ↑↑
a b c a b c ab c a bc
(1)c = b->next; (2)b->next = a; (3)a = b; (4)b = c;
NULL <- 1 <- 2 <- 3 <- 4 5 NULL <- 1 <- 2 <- 3 <- 4 <- 5 NULL <- 1 <- 2 <- 3 <- 4 <- 5 NULL <- 1 <- 2 <- 3 <- 4 <- 5
↑ ↑ ↑ ↑ ↑ ↑ ↑↑ ↑ ↑ ↑↑
a b c a b c ab c a bc
*/
ListNode* reverseList(ListNode* head) {
if(head == NULL || head -> next == NULL)
return head;
ListNode* first = NULL;
ListNode* second = head;
while(second != NULL){
ListNode* third = second -> next;
second -> next = first;
first = second;
second = third;
}
return first;
}
// 使代码更简洁,将参数名改为second
ListNode* reverseList(ListNode* second) {
ListNode* first = NULL;
while(second){
ListNode* third = second -> next;
second -> next = first;
first = second;
second = third;
}
return first;
}
下面我们考虑递归的方法:
/* 例如:
1 -> 2 -> 3 -> 4 -> 5
1. 1 -> 2 -> 3 -> 4 <- 5
递归到最深处为 head = 5,返回后到 head = 4 处:
newHead = 5;
newTail = 4 -> next = 5;
5 -> next = 4;
4 -> next = NULL;
return 5;
2. 1 -> 2 -> 3 <- 4 <- 5
从 head = 4 返回到 head = 3 处
newHead = 5;
newTail = head(3) -> next = 4;
newTail(4) -> next = head(3);
3 -> next = NULL;
return 5;
3. 1 -> 2 <- 3 <- 4 <- 5
从 head = 3 返回到 head = 2处
newHead = 5;
newTail = head(2) -> next = 3;
newTail(3) -> next = head(2);
head(2) -> next = NULL;
return 5;
...
-*/
ListNode* reverseList(ListNode* head) {
if(head == NULL || head -> next == NULL)
return head;
ListNode* newHead = reverseList(head -> next); // 逆置head -> next作为新的头
ListNode* newTail = head -> next; // 新的尾节点为head -> next
newTail -> next = head; // 将该节点逆置
head -> next = NULL;
return newHead; // 返回新的头结点
}