链表中的节点每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;
	}
相关推荐
心仪久了会沦陷3 小时前
C语言数据结构入门——树与二叉树详解:概念、堆实现与链式遍历
c语言·数据结构·算法
码少女5 小时前
数据结构——图的基础
数据结构
Severus_black7 小时前
【C++初阶】list使用及相关实现,思路顺滑流畅!
c语言·数据结构·c++·stl·list
二本咕咕-机械转码9 小时前
FreeRTOS深入解析(八)IPC机制之FromISR详解
数据结构·单片机·链表
1-1=011 小时前
C# 数据结构和特殊类型
数据结构·c#·.net·.netcore
希和202711 小时前
C语言程序设计题|有序数组插入数字冒泡排序
c语言·数据结构·算法
布莱克60521 小时前
C++ 中 map 的 insert 与 emplace:key 已存在时会覆盖吗?
开发语言·数据结构·c++·算法·map
D e re k ZH1 天前
C++ 系统学习手记:从语法细节到工程实践
开发语言·数据结构·c++·算法
zh_xuan1 天前
LeeCode 496. 下一个更大元素I
数据结构·算法·栈·单调栈
白杨尚青1 天前
C++进阶篇(五):红黑树——四条规则、三种插入情况与旋转变色
开发语言·数据结构·c++·stl·红黑树·平衡二叉树