题目描述
将一个链表从m位置反向到n,并在一个通道内完成。例如:
给定1 - > 2 - > 3 - > 4 - > 5 - > NULL,m = 2和n = 4
返回1 - > 4 - > 3 - > 2 - > 5 - > NULL
注意:给定m, n满足以下条件:1 ≤ m ≤ n ≤ 链表长度
解题思路
(1)找到m位置的节点和m位置的前置节点pre
(2)将m位置的next节点插入到pre和pre的next之间,将m的next置为原m的next的next,继续该操作n-m次
代码示例
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
if (head == NULL) return NULL;
ListNode *dummy = new ListNode(0); //使用一个新的链表保存结果(我直接在head上改会报错,原因还没查)
dummy->next = head;
ListNode *pre, *start = head;
for (int i = 1; i < m; i++) {//找到m位置和pre节点
pre = start;
start = start->next;
}
for (int i = m; i < n; i++) {
ListNode *temp = start->next;//找到m的next
start->next = temp->next;//将m的next设为m的next的next
temp->next = pre->next;//将m的next插入pre和pre的next之间
pre->next = temp;
}
return dummy->next;
}
};