Reverse Linked List II(旋转链表的指定部分)
Leetcode
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
旋转链表的有序部分,思路:
- 申请一个辅助链表,将第
m
到第n
个节点依次插入到辅助链表头结点后,完成异地置逆。 - 将辅助链表插回到原链表的
m
到n
之间。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
if(head == nullptr || m >= n)
return head;
ListNode * newHead = new ListNode(0); //原链表前增加头结点
newHead->next = head;
ListNode * tempHead = new ListNode(0); //辅助链表的头结点
ListNode * pre = newHead; //需要置逆的前一个节点
int i = 1; //第i个节点,永远指向需要被删除的那么节点
while(pre->next != nullptr && i < m) //将i指向第m个节点,pre指向第m-1个节点
{
pre = pre->next;
i++;
}
//这里是否需要判断没有到第m个节点?
if(i < m) return head;
ListNode * p = nullptr;
while(i <= n && pre->next != nullptr)
{
p = pre->next;
pre->next = p->next; //在原链表上去掉第i个节点
p->next = tempHead->next;
tempHead->next = p; //将第i个节点添加到辅助链表上
i++;
}
p = tempHead;
while(p->next != nullptr) //p指向辅助链表的最后一个节点
p = p->next;
p->next = pre->next;
pre->next = tempHead->next; //将辅助链表除头结点以外部分插入到原链表pre后面
return newHead->next;
}
};
时间: 2024-10-29 02:00:38