Day9: [LeetCode困难] 25. K 个一组翻转链表

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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值