LeetCode25. K 个一组翻转链表

☆☆☆☆【字节】

很综合的一道题目,用到 [LeetCode206. 反转链表]

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || head.next == null) return head;
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode pre = dummyHead; // pre表示待反转链表部分的头节点的前一个节点
        ListNode end = dummyHead; // end表示待反转链表部分的最后一个节点
        while (end.next != null) {
            for (int i = 0; i < k; i++) {
                end = end.next;
                if (end == null)
                    return dummyHead.next;
            }
            ListNode next = end.next; // 保存一下后半部分的头节点
            end.next = null; // 断开链表
            ListNode start = pre.next; // 反转链表部分的头节点

            pre.next = reverse(start); // 拼接前部分
            start.next = next; // 拼接后部分

            pre = start;  // 更新pre, end 都指向下次待反转链表部分的头节点的前一个节点
            end = start;
        }
        return dummyHead.next;
    }
    // 反转链表
    private ListNode reverse(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode cur = head;
        ListNode pre = null, next = null;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

 

posted @ 2020-12-14 17:10  不学无墅_NKer  阅读(71)  评论(0编辑  收藏  举报