How to reverse a singly-linked list in blocks of some given size in O(n) time in place?

前端 未结 4 828
梦如初夏
梦如初夏 2021-01-13 15:20

I recently encounter an algorithm problem:

Reverse a singly-linked list in blocks of k in place. An iterative approach is preferred.

4条回答
  •  春和景丽
    2021-01-13 15:56

    Here is an iterative way of doing it... you read my full explanation here

    Node reverseListBlocks1(Node head, int k) {
        if (head == null || k <= 1) {
            return head;
        }
    
        Node newHead = head;
        boolean foundNewHead = false;
    
        // moves k nodes through list each loop iteration
        Node mover = head;
    
        // used for reversion list block
        Node prev = null;
        Node curr = head;
        Node next = null;
    
        Finish: while (curr != null) {
    
            // move the mover just after the block we are reversing
            for (int i = 0; i < k; i++) {
                // if there are no more reversals, finish
                if (mover == null) {
                    break Finish;
                }
                mover = mover.next;
            }
    
            // reverse the block and connect its tail to the rest of
            // the list (at mover's position)
            prev = mover;
            while (curr != mover) {
                next = curr.next;
                curr.next = prev;
                prev = curr;
                curr = next;
            }
    
            // establish the new head, if we didn't yet
            if (!foundNewHead) {
                newHead = prev;
                foundNewHead = true;
            }
            // connects previous block's head to the rest of the list
            // move the head to the tail of the reversed block
            else {
                head.next = prev;
                for (int i = 0; i < k; i++) {
                    head = head.next;
                }
            }
        }
    
        return newHead;
    }
    

提交回复
热议问题