一、题目描述:92. 反转链表 II(中等)
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、解题思路
1、找到m的前一个位置front。然后从front->next开始反转,反转m-n个节点
2、注意边界条件m=1和n等于list长度
三、代码
/**
* 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) {
int count = 1;
ListNode * pre = head;
while(count < m-1 && pre != NULL)
{
pre = pre ->next;
count ++;
}
if( pre == NULL)
return head;
ListNode * front = pre;
ListNode * tail = NULL;
if(m == 1)
{
tail = pre;
}
else
{
pre = front->next;
tail = front->next;
//cout<<tail->val<<endl;
}
if(pre == NULL)
return head;
ListNode * next = pre->next;
if(next == NULL)
return head;
//if(m == 1)
// count--;
while(next != NULL && count <= n-1)
{
ListNode * next_next = next->next;
if(m != 1 && count == n-1)
{
cout<< "next"<<next->val<<endl;
break;
}
next->next = pre;
pre = next;
next = next_next;
count ++;
}
/*
if(n-m == 1 && next != NULL)
{
cout<<"reverse n"<<next->val<<pre->val<<endl;
ListNode * next_next = next->next;
next->next = pre;
pre = next;
next = next_next;
}
*/
if(m == 1)
{
tail->next = next;
//head->next = NULL;
return pre;
}
else
{
front->next = pre;
tail->next = next;
}
return head;
}
};