[leetcode] 25. k个一组翻转链表

25. k个一组翻转链表

仍然是链表处理问题,略微复杂一点,边界条件得想清楚,画画图就会比较明确了。

reverse函数表示从 front.next节点开始,一共k个节点做反转。
即: 1>2>3>4>5 ,k = 2。当front为1时,
执行reverse后:

1>3>2>4>5

同上个题一样,申请一个空的(无用的)头指针指向第一个节点,会方便许多。

public ListNode reverseKGroup(ListNode head, int k) {
        ListNode ans = new ListNode(Integer.MAX_VALUE);
        ans.next = head;
        ListNode p = ans;
        while (ok(p.next, k)) {
            p = reverse(p, k);
        }

        return ans.next;
    }

    private boolean ok(ListNode p, int k) {
        while (k > 0 && p != null) {
            p = p.next;
            k--;
        }
        return k == 0;
    }

    private ListNode reverse(ListNode front, int k) {
        ListNode from = front.next;
        ListNode head = from;
        ListNode cur = from.next;
        ListNode tmp = null;
        while (k > 1 && cur != null) {
            tmp = cur.next;
            cur.next = from;

            from = cur;
            cur = tmp;
            k--;
        }
        head.next = cur;
        front.next = from;
        return head;
    }

猜你喜欢

转载自www.cnblogs.com/acbingo/p/9256337.html