题解 | 每K个一组反转链表

import java.util.*;

public class Main {

    // 翻转单个链表

    public static ListNode reverseList(ListNode head) {

        ListNode prev = null, curr = head, next = null;

        while (curr != null) {

            next = curr.next;

            curr.next = prev;

            prev = curr;

            curr = next;

        }

        return prev;

    }

    // K组翻转

    public static ListNode reverseKGroup(ListNode head, int k) {

        ListNode dummy = new ListNode(-1);

        dummy.next = head;

        ListNode pre = dummy, 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 = reverseList(start);

            start.next = next;

            // 移动指针到下一组

            pre = end = start;

        }

        return dummy.next;

    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        // 读入链表

        ListNode dummy = new ListNode(-1);

        ListNode tail = dummy;

        String[] nums = sc.nextLine().split(" ");

        for (String num : nums) {

            tail.next = new ListNode(Integer.parseInt(num));

            tail = tail.next;

        }

        // 读入k

        int k = sc.nextInt();

        // 处理并输出结果

        ListNode result = reverseKGroup(dummy.next, k);

        // 输出结果

        while (result != null) {

            System.out.print(result.val);

            if (result.next != null) System.out.print(" ");

            result = result.next;

        }

        System.out.println();

        sc.close();

    }

}

全部评论

相关推荐

09-12 11:00
门头沟学院 Java
b溃了,早知道不拉扯了
在迎接offer的废...:手中握着有一两个offer才敢拉扯,没保底就别了吧。
我的秋招日记
点赞 评论 收藏
分享
09-01 11:31
门头沟学院 Java
buul:七牛云的吧,感觉想法是好的,但是大家没那么多时间弄他这个啊。。。不知道的还以为他是顶尖大厂呢还搞比赛抢hc,只能说应试者的痛苦考察方是无法理解的,他们只会想一出是一出
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务