LeetCode - Reverse Nodes in k-Group

本文介绍如何解决LeetCode上的一个算法问题,即在给定的链表中反转连续的K个节点。文章详细解释了实现步骤,并通过代码示例展示了具体操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://leetcode.com/problems/reverse-nodes-in-k-group/

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

在reverse的时候,一定要注意指针的变化,最后一个node要一直指向下一个需要被放到前面的node。

下面的代码是,先找到k个node,然后调用reverse函数,这个函数将会把head和tail之间的所有node做reverse,但不包含head和tail,返回reverse后tail之前的那个node。

public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null || head.next==null) return head;
        if(k==1) return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode before = dummy;
        ListNode after = dummy;
        while(after != null){
            int t = k;
            while(t>0){
                if(after == null) return dummy.next;
                after = after.next;
                t--;
            }
            if(after == null) return dummy.next;
            before = reverse(before, after.next);
            after = before;
        }
        return dummy.next;
    }
    
    public ListNode reverse(ListNode head, ListNode tail){
        if(head==tail || head.next==tail || head.next.next==tail) return head;
        //reverse the nodes between head and tail, not include head and tail
        ListNode tvs = head.next.next;
        ListNode last = head.next;
        while(tvs!=tail){
            last.next = tvs.next;
            tvs.next = head.next;
            head.next = tvs;
            tvs = last.next;
        }
        return last;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值