LeetCode 25 K个一组翻转链表

// 按照每K个为一组,记录这组内的头和尾,第一组只需记录翻转后的尾即Tail
// 接下来的每一组记录翻转后头 : nHead 和尾 : nTail.注意更新的顺序



class Solution {
    public ListNode reverseKGroup(ListNode head, int k){
        if (head == null) return null;
        if (head.next == null || k == 1) return head;      
        ListNode pre = null;     
        ListNode p = head;
        ListNode q = null;
        int length = 0;
        while(p != null){
            length ++;
            p = p.next;
        }
        length /= k;
        if (length == 0) return head;
        p = head;
        ListNode oTail = head;
        ListNode nHead = null;
        ListNode nTail = null;   
        int i = 0;
        boolean flag = false;
        while(p != null){
            q = p.next;
            p.next = pre;
            pre = p;
            p = q; 
            i++;
            if (i == k){
                length --;
                if (!flag){
                    head = pre;
                    flag = true;
                    nTail = p; // 第一次只保留尾
                }else {
                    nHead = pre; // 保留头newHead 简称 nHead
                    oTail.next = nHead;// 将上次的尾与这次头相连
                    oTail = nTail; // 更新上次尾oldTail 简称oTail
                    nTail = p; // 更新这次尾newTail 简称 nTail
                }
                if (length == 0){
                    oTail.next = p; // 不足k的部分直接连上
                    return head;
                }
                i = 0;
            }
        }
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/TIMELIMITE/article/details/89413948