Day9: [LeetCode困难] 25. K 个一组翻转链表
题源:
来自leetcode题库:
https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
思路:
这道题虽然难度是困难,但是考察的还是链表的操作,没有任何思考难度。唯一需要注意的就是边界条件什么的。
值得一提的是: 我在写这道题的时候,第一次提交把while(1)写成了for(;; ),然后速度要比while(1)慢一倍吧,估计是编译器会对while(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* reverseKGroup(ListNode* head, int k) {
if(k==1) return head;
ListNode *pre=NULL,*NextPre=NULL,*Next=NULL,*right=head,*left=head,*res=head;
ListNode *temp=new ListNode(-999);
bool first=true;
while(left){
right=left;
for(int i=0;i<k-1;i++){
right=right->next;
if(right==NULL) return res;
}
Next=right->next;
NextPre=left;
while(1){
if(pre!=NULL) pre->next=left->next;
else {
pre=temp;
pre->next=left->next;
}
left->next=right->next;
right->next=left;
left=pre->next;
if(pre->next==right) break;
}
if(first) {
first=false;
res=pre->next;
}
pre=NextPre;
left=pre->next;
}
return res;
}
};