链表中的节点每k个一组翻转

代码求解

要实现每k个一组翻转链表,我们先来手撕一下反转整个链表:

java 复制代码
//反转以a为头节点的链表
	ListNode reverse(ListNode a){
		ListNode pre = null;
		ListNode cur = a;
		ListNode next = a;
		while(cur!=null){
			next = cur.next;
			cur.next = pre;
			pre = cur;
			cur = next;
		}
		return pre;
	}

我们再来手撕一下反转a到b之间的节点

注意是左闭右开区间

java 复制代码
//反转区间[a,b)的节点
	ListNode reverse(ListNode a,ListNode b){
		ListNode pre = null;
		ListNode cur = a;
		ListNode next = a;
		while(cur!=b){
			next = cur.next;
			cur.next = pre;
			pre = cur;
			cur = next;
		}
		return pre;
	}

所以,实现每k个一组反转就是:

java 复制代码
ListNode reverseKGroup(ListNode head,int k){
		if(head == null){
			return null;
		}

		ListNode a = head;
		ListNode b = head;

		for(int i=0;i<k;i++){
			if(b==null){
				return head;
			}
			b=b.next;
		}
		//反转[a,b)区间的链表,得到新的头节点
		ListNode newHead = reverse(a,b);
		//递归处理剩余区间,拼接链表
		a.next = reverseKGroup(b,k);
		return newHead;
	}


	ListNode reverse(ListNode a,ListNode b){
		ListNode pre = null;
		ListNode cur = a;
		ListNode next = a;
		
		while(cur!=b){
			next = cur.next;
			cur.next = pre;
			pre = cur;
			cur = next;
		}

		return pre;
	}
相关推荐
切糕师学AI21 分钟前
环形缓冲区(Ring Buffer / Circular Buffer)详解:原理、优势、应用与高性能实现
数据结构·环形缓冲区
WolfGang0073211 小时前
代码随想录算法训练营 Day50 | 图论 part08
数据结构·算法·图论
晚枫歌F3 小时前
最小堆定时器
数据结构·算法
嫩萝卜头儿4 小时前
2 - 复杂度收尾 + 链表经典OJ
数据结构·算法·链表·复杂度
样例过了就是过了5 小时前
LeetCode热题100 分割等和子集
数据结构·c++·算法·leetcode·动态规划
木木_王5 小时前
嵌入式Linux学习 | 数据结构 (Day05) 栈与队列详解(原理 + C 语言实现 + 实战实验 + 易错点剖析)
linux·c语言·开发语言·数据结构·笔记·学习
北顾笙9806 小时前
day38-数据结构力扣
数据结构·算法·leetcode
m0_629494736 小时前
LeetCode 热题 100-----14.合并区间
数据结构·算法·leetcode
@小码农6 小时前
2026年3月Scratch图形化编程等级考试一级真题试卷
开发语言·数据结构·c++·算法
_日拱一卒8 小时前
LeetCode:226翻转二叉树
数据结构·算法·leetcode