206.反转链表

Problem: 206. 反转链表

思路

这个题干想很费脑子,多个指针变来变去可记不住,浪费一个小时也没调对,还是得画下图,一步一步规划代码,类似数形结合思想,这叫码形结合思想

解题过程

开头额外处理,剩下的节点循环处理即可

复杂度

  • 时间复杂度: $O(n)$ n次处理指针过程
  • 空间复杂度: $O(1)$

Code

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
//! 码形结合思想 n,1
class Solution {
public:
ListNode *reverseList(ListNode *head) {
if (head == nullptr) {
return nullptr;
}

ListNode *node = head;
ListNode *pre;
ListNode *nex;
pre = node;
if (node->next == nullptr) {
return node;
}
node = node->next;
nex = node->next;
node->next = pre;
pre->next = nullptr;
pre = node;
node = nex;
while (node != nullptr) {
nex = node->next;
node->next = pre;
pre = node;
node = nex;
}
return pre;
}
};
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
//! 码形结合思想 n,1 上个答案对不必要逻辑和变量的缩减
class Solution {
public:
ListNode *reverseList(ListNode *head) {

ListNode *node = head;
ListNode *pre = nullptr;
ListNode *nex;
pre = node;
if (node->next == nullptr) {
return node;
}
node = node->next;
nex = node->next;
node->next = pre;
pre->next = nullptr;
pre = node;
node = nex;
while (node != nullptr) {
nex = node->next;
node->next = pre;
pre = node;
node = nex;
}
return pre;
}
};
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
//! 错误答案,第一遍给干成循环移动链表的,好好审题,浪费时间了
class Solution {
public:
ListNode *reverseList(ListNode *head) {
if (head == nullptr) {
return nullptr;
}

ListNode *node1 = head;

ListNode *tail = head;
while (tail->next != nullptr) {
tail = tail->next;
}
ListNode *node2 = tail;

while (node1->next != tail) {
node2->next = node1;
node2 = node2->next;
node1 = node1->next;
}
node2->next = node1;
node1->next = nullptr; // 破坏循环链表

return tail;
}
};