Reverse Nodes in k-Group

Reverse Nodes in Pairs (LC.24)

Given a linked list, swap every two adjacent nodes and return its head.

Example

I: 1->2->3->4
O: 2->1->4->3

Analysis

Give a dummy head and write a swap next 2 helper.

Code

public ListNode swapPairs(ListNode head) {
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode current = dummy;
    while (current != null) {
        current = swapNextPair(current);
    }
    return dummy.next;
}

// swap pair then return the start of next pair
// base -> a -> b -> c
private ListNode swapNextPair(ListNode base) {
    if (base.next == null || base.next.next == null) {
        return null; // no more pairs to swap
    }
    // swap
    ListNode a = base.next;
    ListNode b = base.next.next;
    ListNode c = base.next.next.next;
    base.next = b;
    b.next = a;
    a.next = c;    
    return a;
}

Reverse Nodes in k-Group (LC.25)

Given a linked list, reverse the list in a group of k nodes.

Assume k is a valid number. If the length of the leftover nodes is less than k, do nothing.

Example

Approach

Code

Last updated