โ† Back to Index

๐Ÿ“š In-Place Manipulation of a Linked List โ€“ Java Cheat Sheet (One Page)

๐Ÿ“Œ What Is It?

In-place manipulation of a linked list involves modifying the structure of the list without using extra space. Common operations include reversing, reordering, or merging nodes.

๐Ÿงฑ Pattern Template

// Reverse a Linked List
public ListNode reverse(ListNode head) {
    ListNode prev = null;
    while (head != null) {
        ListNode next = head.next;
        head.next = prev;
        prev = head;
        head = next;
    }
    return prev;
}

// Reorder a Linked List
public void reorderList(ListNode head) {
    if (head == null || head.next == null) return;

    // Find the middle of the list
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }

    // Reverse the second half
    ListNode second = reverse(slow.next);
    slow.next = null;

    // Merge two halves
    ListNode first = head;
    while (second != null) {
        ListNode temp1 = first.next, temp2 = second.next;
        first.next = second;
        second.next = temp1;
        first = temp1;
        second = temp2;
    }
}

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Reverse a Linked List

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

๐Ÿ’ก Pro Tips