链表中的节点每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;
	}
相关推荐
琢磨先生David3 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
qq_454245033 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝3 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
岛雨QA3 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc3 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
wefg13 天前
【算法】单调栈和单调队列
数据结构·算法
岛雨QA3 天前
图「Java数据结构与算法学习笔记12」
数据结构·算法
czxyvX3 天前
020-C++之unordered容器
数据结构·c++
岛雨QA3 天前
多路查找树「Java数据结构与算法学习笔记11」
数据结构·算法
AKA__Zas3 天前
初识基本排序
java·数据结构·学习方法·排序