链表内指定区间反转
- 描述
将一个节点数为 size 链表 m 位置到 n 位置之间的区间反转,要求时间复杂度 O(n),空间复杂度 O(1)。
例如:
给出的链表为 1→2→3→4→5→NULL, m=2,n=4,
返回 1→4→3→2→5→NULL.
例如:
给出的链表为 1→2→3→4→5→NULL, m=2,n=4,
返回 1→4→3→2→5→NULL.
数据范围: 链表长度 0<size≤1000,0<m≤n≤size,链表中每个节点的值满足∣val∣≤1000
要求:时间复杂度 O(n) ,空间复杂度 O(n)
进阶:时间复杂度 O(n),空间复杂度 O(1)
- 示例1
输入:
{1,2,3,4,5},2,4
返回值:
{1,4,3,2,5}
- 示例2
输入:
{5},1,1
返回值:
{5}
- 算法思想
首先需要找到开始翻转的节点以及其前驱。找到后指针的指向情况如下图。

接下来进行以下步骤
cur->next=temp->next
temp->next=pre->next
pre->next=temp
即如下图所示
翻转完后为
这样就做到了2,3之间的局部翻转,需要注意的是pre与cur所指向的元素从始至终都没有变化,temp始终指向cur的后继。
接下来再做2,3,4之间的翻转
仍然执行以下步骤
cur->next=temp->next
temp->next=pre->next
pre->next=temp
即如下图所示

翻转完后为
这样就完成了整体的反转。
- 代码
1 /** 2 * struct ListNode { 3 * int val; 4 * struct ListNode *next; 5 * }; 6 */ 7 8 #include <cstdlib> 9 class Solution { 10 public: 11 /** 12 * 13 * @param head ListNode类 14 * @param m int整型 15 * @param n int整型 16 * @return ListNode类 17 */ 18 ListNode* reverseBetween(ListNode* head, int m, int n) { 19 //创建一个头结点,便于处理开始翻转的位置在第一个节点的位置 20 ListNode *res=(ListNode*)malloc(sizeof(ListNode)); 21 res->next=head; 22 ListNode* pre=res; 23 ListNode* cur=head; 24 //找到开始翻转的节点以及它的前驱 25 for(int i=1;i<m;i++){ 26 pre=cur; 27 cur=cur->next; 28 } 29 //开始执行翻转 30 for(int i=m;i<n;i++){ 31 ListNode *temp=cur->next; 32 cur->next=temp->next; 33 temp->next=pre->next; 34 pre->next=temp; 35 } 36 //返回头节点 37 return res->next; 38 } 39 };