K组翻转链表

力扣链接

题目描述:
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。

k 是一个正整数,它的值小于或等于链表的长度。

如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

在这里插入图片描述
大题思路如下:
在这里插入图片描述

翻转局部链表,也就是简单的翻转链表

1.定一个傀儡节点temp,让pre 和 cur执行傀儡节点;
2.让cur先走k步,然后让start指向per.next,end指向cur,cur指向cur.next;
3.翻转局部后,在重新拼接

在这里插入图片描述
在这里插入图片描述

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null || head.next == null) return head;

        
        ListNode temp = new ListNode(-1);
        temp.next = head;
        ListNode cur = temp;
        ListNode pre = temp;
        while(cur.next != null){
            int n = k;
            while(n != 0){
                cur = cur.next;
                if(cur == null){
                    return temp.next;
                }
                n--;
            }
            ListNode start = pre.next;
            ListNode end = cur;
            cur  = cur.next;
            end.next = null;
            pre.next =  reverse(start);
            start.next = cur;
            pre = start;
            cur = pre;
            end = pre;

        }
        return temp.next;
    }

    public ListNode reverse(ListNode head){
        ListNode cur = null;
        ListNode curNext = head;
        while(curNext != null ){
           ListNode next = curNext.next;
            curNext.next = cur;
            cur = curNext;
            curNext = next;
        }
        return cur;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值