Leetcode面试经典150题-25.K个一组反转链表

解法都在代码里,不懂就留言或者私信

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        /**1个1组反转吗?神经病啊 */
        if(k == 1) {
            return head;
        }
        /**题目已经给出k<=n了,所以无需验证k是否大于长度*/
        int count = 0;
        ListNode cur = head;
        /**当前区间的头 */
        ListNode curHead = head;
        /**反转之后链表的头 */
        ListNode newHead = null;
        /**上个区间反转之后的结尾 */
        ListNode preLast = null;
        /**下一个节点用于遍历 */
        ListNode next = null;
        while(cur != null) {
            /**路过节点就统计,而不是走一步统计,这样比较方便 */
            count ++;
            /**拿到当前的下个节点,因为cur的next指针会发生变化,所以需要提前拿到 */
            next = cur.next;
            /**如果够了k个 */
            if(count == k) {
                /**断开和后面的连接,方便当前区间的反转 */
                cur.next = null;
                /**反转当前区间 */
                ListNode curHeadReverse = reverse(curHead);
                /**如果前一个区间的尾巴不为空(当前不是第一个区间) */
                if(preLast != null) {
                    preLast.next = curHeadReverse;
                }
                /**如果新的头为空(当前是第一个区间),给新的头赋值 */
                if(newHead == null) {
                    newHead = curHeadReverse;
                }
                /**preLast是给下个区间用的,它的next指向下个区间反转之后的头 */
                preLast = curHead;
                /**当前区间的尾巴指向下个区间目前的头(反转之前的) */
                curHead.next = next;
                /**下个区间的头*/
                curHead = next;
                /**当前k个结束,count归0 */
                count = 0;
            }
            cur = next;
        }
        return newHead;
    }
    /**经典的反转链表的题 */
    public ListNode reverse(ListNode head) {
        ListNode cur = head;
        ListNode pre = null;
        ListNode next = null;
        while(cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

运行结果

肯定是最优解了,但是其中的遍历可以删除一点,其实无所谓的

相关推荐
mjhcsp9 分钟前
莫比乌斯反演总结
c++·算法
dazzle38 分钟前
Python数据结构(五):队列详解
数据结构·python
爱编码的傅同学44 分钟前
【今日算法】LeetCode 25.k个一组翻转链表 和 43.字符串相乘
算法·leetcode·链表
stolentime1 小时前
P14978 [USACO26JAN1] Mooclear Reactor S题解
数据结构·c++·算法·扫描线·usaco
老歌老听老掉牙1 小时前
差分进化算法深度解码:Scipy高效全局优化实战秘籍
python·算法·scipy
dazzle1 小时前
Python数据结构(四):栈详解
开发语言·数据结构·python
CSDN_RTKLIB1 小时前
C++多元谓词
c++·算法·stl
LYS_06181 小时前
寒假学习(2)(C语言2+模数电2)
c语言·学习·算法
listhi5201 小时前
压缩感知信号重构的块稀疏贝叶斯学习(BSBL)算法:原理、实现与应用
学习·算法·重构
摸个小yu1 小时前
【力扣LeetCode热题h100】哈希、双指针、滑动窗口
算法·leetcode·哈希算法