链表内指定区域反转
[题](链表内指定区间反转_牛客题霸_牛客网 (nowcoder.com))
代码
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/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <cstddef>
class Solution {
public:
/**
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
ListNode* reverseBetween(ListNode* head, int m, int n) {
// write code here
ListNode* temHead=new ListNode(0);//c++的创建方法,0是data域
//创建虚拟头节点
//操作头节点方便,比如如果反转第一个元素
temHead->next=head;
ListNode* pre=temHead;
ListNode* cur=head;
//两个指针用于操作来链表
ListNode* tem=nullptr;
//用于存放cur->next
for (int i = 1; i < m; ++i) {
pre=pre->next;
cur=cur->next;
}
//使节点移动
for (int i=0; i<n-m;++i) {
tem=cur->next;
cur->next=tem->next;
//始终让cur->next指向的使next->xext;
tem->next=pre->next;
//让反转的指针,指向pre->next实现反转
pre->next=tem;
//再让pre指向tem保持连接
}
return temHead->next;
}
};提示
理解
- 先遍历到反转区域
- 使用虚拟头节点
问题
为什么不用判断
cur->next->next
是不是越界?因为不会越界
如果使用的区域刚好是整个链表
那么当要反转最后一个节点的时候,也就是最后一次
cur->next->next=
nullptr
链表内指定区域反转
https://tsy244.github.io/2023/04/10/算法/newcoder/链表内指定区域反转/