【链表转置】Reverse Nodes in k-Group

本文介绍了一种算法,该算法可以将链表每K个节点为一组进行反转,并保持剩余节点顺序不变。通过原地反转链表节点实现,不改变节点值,仅调整节点连接顺序,并限制额外内存消耗。提供了具体的Java实现代码。

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

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将链表原地转置,使用一个新节点,将原先的链表元素插入到头结点之后

public class Solution {
    public ListNode reverse(ListNode head){
        ListNode p = head;
        ListNode pre = new ListNode(0);
        head = pre;
        
        while(p != null){
            ListNode r = p.next;
            p.next = head.next;
            head.next = p;
            
            p = r;
        }
        pre = pre.next;
        head.next = null;
        return pre;
    }
    
    public ListNode reverseKGroup(ListNode head, int k) {//k个元素判断一次
        ListNode p1 = head;
        if(k<=1 || head == null) return head;
        
        int count = 0;
        ListNode pre = null;
        while(p1 != null && count < k){
            count++;
            pre = p1;
            p1 = p1.next;
        }
        if(count < k) return head;
        
        pre.next = null;
        pre = reverse(head);//head转置后变为新链表的最后一个节点,返回新链表的头结点
        
        head.next = reverseKGroup(p1, k);
        return pre;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值