Day13: [LeetCode中等] 92. 反转链表 II
题源:
来自leetcode题库:
https://leetcode-cn.com/problems/reverse-linked-list-ii/
思路:
首先找到第m个节点,设为指针p,然后把m+1到n个的节点插过去,需要注意的是,每次插入要更新p为之前的前置节点。再一个需要注意的是,当m为1的时候要特殊处理一下,总之注意边界条件。
代码:
dirty code凑合看吧
/**
* 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||head->next==NULL||m==n) return head;
ListNode *p=head,*q=head,*pre=head;
for(int i=0;i<m-1;i++){
pre=p;
p=p->next;
}
q=p->next;
auto rear=p;
for(int j=0;j<n-m;j++){
rear->next=q->next;
q->next=p;
if(m==1){
pre=q;
head=q;
}else{
pre->next=q;
}
q=rear->next;
if(m==1) p=pre;
else p=pre->next;
if(!q) break;
}
return head;
}
};