算法通关村第二关|黄金挑战|K个一组进行反转

本文介绍了两种在链表中按K个一组进行反转的方法:头插法通过多次移动节点实现,而穿针引线法则通过找到区间边界并断开连接进行反转。作者还提供了反转链表的基本实现。
摘要由CSDN通过智能技术生成

K个一组进行反转

1.头插法

public ListNode reverseKGroup(ListNode head, int k) {
	ListNode dummyNode = new ListNode(0);
    dummyNode.next = head;
    ListNode cur = head;
    // 计算链表长度
    int len = 0;
    while (cur != null) {
        len++;
        cur = cur.next;
    }
    // 计算有几组
    int n = len / k;
    ListNode pre = dummyNode;
    cur = head;
    // 一共进行n次反转
    for (int i = 0; i < n; i++) {
        // 每次反转操作将cur移动k-1次
        for (int j = 0; j < k - 1; j++) {
            ListNode next = cur.next;
            cur.next = cur.next.next;
            next.next = pre.next;
            pre.next = next;
        }
        pre = cur;
        cur = cur.next;
    }
    return dummyNode.next;
}

2.穿针引线法

public ListNode reverseKGroup(ListNode head, int k) {
	ListNode dummyNode = new ListNode(0);
    dummyNode.next = head;
    ListNode pre = dummyNode;
    ListNode end = dummyNode;
    while (end.next != null) {
        // 找到每次处理的一段区间的末尾处,移动k次
    	for (int i = 0; i < k && end != null; i++) {
            end = end.next;
        }
        if (end == null) {
            break;
        }
        ListNode start = pre.next;
        ListNode next = end.next;
        // 与后边的链表断开
        end.next = null;
        // 调用反转方法,将断开的这一段链表反转,并且和前边的链表相连接
        pre.next = reverse(start);
        // 现在start是这段链表的末尾处,将其与后边的链表相连接
        start.next = next;
        // 把pre和end指针移动到下一个区间的前一个位置
        pre = start;
        end = pre;
    }
    return dummyNode.next;
}

// 反转实现
private ListNode reverse(ListNode head) {
	ListNode pre = null;
	ListNode curr = head;
	while (curr != null) {
        ListNode next = curr.next;
        curr.next = pre;
        pre = curr;
        curr = next;
    }
	return pre;
}

如果对您有帮助,请点赞关注支持我,谢谢!❤
如有错误或者不足之处,敬请指正!❤

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值