LeetCode--HOT100题(31)

目录

  • 题目描述:25. K 个一组翻转链表(困难)
    • 题目接口
    • 解题思路
    • 代码
  • PS:

题目描述:25. K 个一组翻转链表(困难)

给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。

k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
LeetCode做题链接:LeetCode-K 个一组翻转链表

示例 1:
LeetCode--HOT100题(31)_第1张图片

输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]

示例 2:
LeetCode--HOT100题(31)_第2张图片

输入:head = [1,2,3,4,5], k = 3
输出:[3,2,1,4,5]

提示:

链表中的节点数目为 n
1 <= k <= n <= 5000
0 <= Node.val <= 1000

进阶: 你可以设计一个只用 O(1) 额外内存空间的算法解决此问题吗?

题目接口

/**
 * 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) {

    }
}

解题思路

参考题解:图解 K 个一组翻转链表(里面有图解)
LeetCode--HOT100题(31)_第3张图片

代码

/**
 * 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) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;

        ListNode pre = dummy;
        ListNode end = dummy;

        while (end.next != null) {
            for (int i = 0; i < k && end != null; i++) end = end.next;
            if (end == null) break;
            ListNode start = pre.next;
            ListNode next = end.next;
            // 截断链表
            end.next = null;
            // 列表反转,并且对接截断的部分
            pre.next = reverse(start);
            start.next = next;
            pre = start;

            end = pre;
        }
        return dummy.next;
    }

	// 链表反转
    private ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }
        return pre;
    }
}

成功!
LeetCode--HOT100题(31)_第4张图片

PS:

感谢您的阅读!如果您觉得本篇文章对您有所帮助,请给予博主一个喔~

你可能感兴趣的:(LeetCodeHot100,leetcode,算法)