链表中的节点每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;
	}
相关推荐
布莱克6051 小时前
理解B+树:原理、特性与应用场景
数据结构·数据库·mysql
晚风叙码3 小时前
C++哈希表实现:开放定址法和链地址法 (哈希桶)
数据结构·c++·哈希算法·散列表
imaol13 小时前
哈希表--数据结构
数据结构·散列表
Nil20816 小时前
leetcode 160相交链表
算法·leetcode·链表
Herbert_hwt17 小时前
C语言零基础入门:循环控制与数据类型详解
c语言·数据结构·算法
晚风醉蝶18 小时前
1-6-插入排序-InsertionSort
java·数据结构·排序算法
Tyler_TXZ19 小时前
C++C语言之——二叉树
c语言·开发语言·数据结构·c++·二叉树
有点。19 小时前
C++二叉树二(练习题)
数据结构·c++·算法·图论
LuminousCPP19 小时前
栈和队列专题(一):LeetCode 20. 有效的括号
数据结构·经验分享·笔记·leetcode·手写栈
白狐_79821 小时前
408 数据结构|线索二叉树两题详解:先序线索化后的空链域 + 中序前驱/后继判断
c语言·数据结构·链表