时间轴

2025-11-20

init


题目:


链表的题目中一般不能直接更改结点的值。
使用头插法反转链表,创建一个虚拟头节点会避免一些特殊情况,另外最后不能返回head,而是virt_head->next,因为head可能会因为交换而发生变化。

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
struct ListNode {
int val;
ListNode *next;
ListNode()
: val(0)
, next(nullptr)
{
}
ListNode(int x)
: val(x)
, next(nullptr)
{
}
ListNode(int x, ListNode *next)
: val(x)
, next(next)
{
}
};

class Solution {
public:
ListNode *reverseBetween(ListNode *head, int left, int right)
{
int index = 0;
ListNode *virt_head = new ListNode;
virt_head->next = head;
ListNode *p = virt_head, *q;

while (p != nullptr) {
if (index + 1 == left) {
break;
}
index++;
p = p->next;
}
q = p;
while (q != nullptr) {
if (index == right) {
break;
}
index++;
q = q->next;
}
ListNode *tmp;
while (p->next != q) {
tmp = p->next;
p->next = tmp->next;
tmp->next = q->next;
q->next = tmp;
}
head = virt_head->next;
delete virt_head;
return head;
}
};