版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/artisans/article/details/88926124
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* pre_first = 0, *next_last = 0;
int i = 0;
ListNode* cur = head;
while (cur)
{
i++;
if (m == i)
{
ListNode* pre = 0;
ListNode* old_head = cur;
while (i <= n)
{
i ++;
ListNode* TMP = cur->next;
cur->next = pre;
pre = cur;
cur = TMP;
}
/*
反转之后,pre为反转的那段的头结点,old_head为尾结点
*/
if(pre_first) pre_first->next = pre;
old_head->next = cur;
if (pre_first == nullptr)
{
return pre;
}
}
else
{
pre_first = cur;
cur = cur->next;
}
}
return head;
}
};