

Leetcode 25 Reverse Nodes in k-Group 题解分析-再解分析
source link: https://nicksxs.me/2024/01/21/Leetcode-25-Reverse-Nodes-in-k-Group-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Leetcode 25 Reverse Nodes in k-Group 题解分析-再解分析
上一次主要是给了一个解题方案,没有具体讲解,这次又做到了就来看下几种方案,链表转置一直是我比较疑惑的问题,特别是边界处理,而这个问题要把难度加大了
我先讲一下我一开始的思路和解题方法,首先就是写一个转置方法,就处理 k 个一组的内部转置,然后外部循环处理分组以及前后连接等问题,但是这里就涉及到一个问题,就是前后连接的话对于整个链表头,也就是第一个 k 元素组来说,头是个空的,就需要额外处理,一开始就是用判空做额外处理,然后在前后连接的时候也有一些困扰,看了自己的代码库发现其实之前也做过,而且发现这个思路跟以前做的还是一样的,只不过在处理 k 个元素内部的转置的时候有了点差异
一开始的思路是这样的,想了下其实还是比较有问题,从处理难度上来说,在 k 组内处理的时候一开始 A 节点会是悬空的,然后得处理到组内最后一个元素的时候再接上,逻辑会更复杂,而另一种思路就是直接把 A 先挪到 C 后面,这样每次只需要移动一个,可能思路上会更清晰一点
也就是这样的,这种方案就是之前发过的题解代码,上一篇
而最后这种则代码会简单一些,但是需要一定的理解成本,比较重要的一点是我们加了个虚拟的头结点,第一步会先获取下链表的总长度,然后在内循环里处理转置,重点就是分四步,
也就是图里的,第一步先把 cur 的下一个节点设置成 next 的 next 节点,这里就是图里 A 连接到 C,第二步是把 next 的 next 节点设置成虚拟头的 next节点,第三步是把 pre 的next 节点设置成 next,第四步是 next 往后移动
cur.next = next.next;
next.next = pre.next;
pre.next = next;
next = cur.next;
在备注下代码
Recommend
-
5
Leetcode 48 旋转图像(Rotate Image) 题解分析 Posted on 2021-05-01...
-
9
Leetcode 42 接雨水 (Trapping Rain Water) 题解分析 Posted on 2021-07-04 In Java , leetcode Views: 52 Views: 57 Dis...
-
4
Leetcode 028 实现 strStr() ( Implement strStr() ) 题解分析 发表于 2021-10-31 分类于 Java , leetcode 阅读次数: 3...
-
7
Leetcode 053 最大子序和 ( Maximum Subarray ) 题解分析 发表于 2021-11-28 分类于 Java , leetcode 阅读次数: 14 阅读...
-
3
再解 JavaScript 原型与原型链发布于 2 月 2 日JavaScript 原型与原型链虽然是一个老生常谈的话题,但依然困惑着很多人,今天我再来从另一个角度谈谈这个问题。...
-
13
Leetcode 20 有效的括号 ( Valid Parentheses *Easy* ) 题解分析 2022-07-02 Java ,
-
6
Leetcode 1260 二维网格迁移 ( Shift 2D Grid *Easy* ) 题解分析 2022-07-22 7 9
-
5
Leetcode 278 第一个错误的版本 ( First Bad Version *Easy* ) 题解分析You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check...
-
6
Leetcode 1862 向下取整数对和 ( Sum of Floored Pairs *Hard* ) 题解分析Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums....
-
8
Reverse alternate nodes in Linked ListOctober 07, 2023 |1.1K ViewsPROBLEM OF THE DAY: 06/10/2023 | Reverse alternate nodes in Linked ListProblem of the Day, linked-list, Data Structure and Alg...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK