LeetCode-9

92. 反转链表 II

思路

  1. 两个指针a、b,分别找到被反转的第一个结点的前一个结点,被反转的结点的最后一个结点,(在开头设置一个哑结点,防止被反转的第一个结点是头结点)
  2. 再来一个指针c,保存被反转的最后一个结点的next,然后把最后一个结点的next设为null
  3. 反转链表,然后把新链表的head接回去,把c接回到末尾
  4. 返回哑结点的next,不能返回head,因为反转以后,head有可能不是head了

AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* dummy = new ListNode(0), *a, *b, *c;
dummy->next = head;
a = b = c = dummy;
for (int i = 0; i < m - 1; i++) {
a = a->next;
b = b->next;
}
for (int i = 0; i < n - m + 1; i++) {
b = b->next;
}
c = b->next;
b->next = NULL;
a->next = reverseList(a->next);
while (a->next != NULL) {
a = a->next;
}
a->next = c;
return dummy->next;
}
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode *temp = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return temp;
}
};

15. 三数之和

阅读更多