25. Reverse Nodes in k-Group

本文介绍了一种算法,该算法将链表中的节点以K个为一组进行翻转,并返回修改后的链表。讨论了如何处理节点数量不是K的倍数的情况,并提供了两种实现方法:一种使用迭代,另一种采用递归方式。

摘要生成于 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


以K个为一组,基本操作时反转单链表,每组的前驱需要保存,做完反转操作以后本组原头结点成为下一组的前驱,后继也可以在反转链表的操作中找到,回忆反转单链表,最后p1是新头结点,p2访问到反转前的尾节点下一个位置,在这里即可以作为下一组反转的开始节点。

这样的操作需要多少次,可以先遍历得到总节点数以后计算出来。

public class Solution {
    ListNode pre=null;
	ListNode nextstart=null;
	
	public ListNode reverseKGroup(ListNode head, int k)
	{
		if(k<2)
			return head;
		int cnt=0;
		ListNode n=head;
		while(n!=null)
		{
			cnt++;
			n=n.next;
		}
		
		ListNode dummy=new ListNode(-1);
		dummy.next=head;
		pre=dummy;
		
		n=head;
		nextstart=head;
		
		for(int i=0;i<cnt/k;i++)
		{
			reverselist(nextstart, k-1);
		}
		
		pre.next=nextstart;
		
		return dummy.next;
	}
	
	public void reverselist(ListNode head,int times)
	{
		ListNode p1=head;
		ListNode p2=p1.next;
		ListNode p3=null;
		int count=0;
		
		while(p2!=null)
		{
			p3=p2.next;
			p2.next=p1;
			p1=p2;
			p2=p3;
			count++;
			if(count==times)
			{
				pre.next=p1;
				pre=head;
				nextstart=p2;
				return ;
			}
		}
	}
}

--------------------------------------------------------------------------------------------------------------------------------

递归版本,摘自https://discuss.leetcode.com/topic/7126/short-but-recursive-java-code-with-comments

public ListNode reverseKGroup(ListNode head, int k) {
    ListNode curr = head;
    int count = 0;
    while (curr != null && count != k) { // find the k+1 node
        curr = curr.next;
        count++;
    }
    if (count == k) { // if k+1 node is found
        curr = reverseKGroup(curr, k); // reverse list with k+1 node as head
        // head - head-pointer to direct part, 
        // curr - head-pointer to reversed part;
        while (count-- > 0) { // reverse current k-group: 
            ListNode tmp = head.next; // tmp - next head in direct part
            head.next = curr; // preappending "direct" head to the reversed list 
            curr = head; // move head of reversed part to a new node
            head = tmp; // move "direct" head to the next node in direct part
        }
        head = curr;
    }
    return head;
}


1->2->3->4->5
对4->5执行完毕之后,依次把1、2、3挂到它的前面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值