leetcode92. 反转链表 II medium
题目描述:
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
解题思路:
解法1:
虽然题目没有要求检查错误输入,但是还是要检查的。
首先加一个dummy头节点,为了应对从1位置开始反转的情况。其次 我们需要记录,3个节点
fpre: 要反转部分的前一个节点
tonext:要反转部分的后一个节点
tail:反转部分的尾部,也就是反转前的反转部分的第一个节点。(反转后的头部自然是pre)
解法2: 采用头插法实现反转(这个也还行,上面的因为知识连贯所以好记)
代码:
/**
* 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) {
ListNode *dummy=new ListNode(-1),*fpre= nullptr,*tonext=nullptr;
dummy->next=head;
int len=-1; //dummy是第0号节点
ListNode *cur=dummy;
while(cur){
++len;
fpre= len==m-1?cur:fpre;
tonext= len==n+1?cur:tonext;
cur=cur->next;
}
if(m>n || m<1 || n>len)
return head; //非法输入
ListNode * tail = fpre->next;
cur=tail;
ListNode *pre=nullptr,*after=nullptr;
int change_len=n-m+1; // 要反转的节点个数
while(change_len){ //因为已经检查过非法输入了,所以不用 检查cur是否为空
after=cur->next;
cur->next=pre;
pre=cur;
cur=after;
--change_len;
}
fpre->next=pre;
tail->next=tonext;
return dummy->next;
}
};
代码2:
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
/*
实现思路 :以1->2->3->4->5, m = 2, n=4 为例:
定位到要反转部分的头节点 2,head = 2;前驱结点 1,pre = 1;
当前节点的下一个节点3调整为前驱节点的下一个节点 1->3->2->4->5,
当前结点仍为2, 前驱结点依然是1,重复上一步操作。。。
1->4->3->2->5.
*/
if (!head || left <= 0 || left >= right)
return head;
ListNode dummy(0, head);
ListNode* pre = &dummy;
for (int i = 0; i < left - 1 && pre; i++)
pre = pre->next;
if (!pre)
return head;
ListNode* cur = pre->next;
for (int i = left; i < right && cur && cur->next; i++)
{
ListNode* tmp= cur->next;
cur->next = tmp->next;
tmp->next = pre->next;
pre->next = tmp;
}
return dummy.next;
}
};