链表中的节点每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;
	}
相关推荐
小妖6663 小时前
js 实现快速排序算法
数据结构·算法·排序算法
独好紫罗兰6 小时前
对python的再认识-基于数据结构进行-a003-列表-排序
开发语言·数据结构·python
wuhen_n6 小时前
JavaScript内置数据结构
开发语言·前端·javascript·数据结构
2401_841495646 小时前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列
独好紫罗兰6 小时前
对python的再认识-基于数据结构进行-a002-列表-列表推导式
开发语言·数据结构·python
2401_841495646 小时前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
数智工坊7 小时前
【数据结构-树与二叉树】4.5 线索二叉树
数据结构
数智工坊7 小时前
【数据结构-树与二叉树】4.3 二叉树的存储结构
数据结构
独好紫罗兰7 小时前
对python的再认识-基于数据结构进行-a004-列表-实用事务
开发语言·数据结构·python
铉铉这波能秀7 小时前
LeetCode Hot100数据结构背景知识之列表(List)Python2026新版
数据结构·leetcode·list