题解 | #牛群的重新分组#

牛群的重新分组

https://www.nowcoder.com/practice/267c0deb9a6a41e4bdeb1b2addc64c93

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if (k == 1) {
            return head;
        }
        ListNode s = new ListNode(-1);
        s.next = head;
        ListNode ans = s;
        int cnt = 0;
        ListNode t = head;
        boolean flag = false;
        ListNode x = null;
        while (s != null) {
            cnt++;
            s = s.next;
            if (s == null) {
                break;
            }
            if ((cnt % k) == 0) {
                if (!flag) {
                    x = s;
                    flag = true;
                }
                ans.next = s;
                ans = t;
                ListNode next = s.next;
                reverse(t, next);
                t = next;
                s = next;
                cnt++;
            }
        }
        return x;
    }

    public ListNode reverse(ListNode head, ListNode end) {
        ListNode pre = end;
        while (head != end) {
            ListNode next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return head;
    }
}

链表的题还是绕啊。先画图理清楚逻辑,再写代码。然后考虑边界和特殊情况

全部评论

相关推荐

宇信外包 Java 7.5k
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务