মূল কনটেন্টে যান
🌍
গ্লোবাল DSA
প্যাটার্নটপিক 3 · Linked Lists

3.3 In-Place Reversal

চিনবেন কীভাবে
"reverse list", "reverse in k-group", "reorder" — the prev/cur/next three-pointer dance, O(1) space
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন

Demo: Reverse Nodes in k-GroupLC 25 (Hard — Meta High)

Statement (Demo): Given the head of a linked list and an integer k, reverse the nodes k at a time. If fewer than k nodes remain at the end, leave them as they are. Return the new head. Example: head=[1,2,3,4,5], k=2[2,1,4,3,5] | ⚡ n ≤ 5000, 1 ≤ k ≤ n

Approach: First count whether k nodes exist — if not, leave that part alone. If they do, solve the rest recursively first, then reverse the current k nodes with the standard reversal and attach them to that result.

function reverseKGroup(head, k) {
  let count = 0,
    node = head;
  while (node && count < k) {
    node = node.next;
    count++;
  }
  if (count < k) return head; // fewer than k left → unchanged
  let prev = reverseKGroup(node, k); // solve the next group first
  let cur = head;
  while (count--) {
    const next = cur.next;
    cur.next = prev;
    prev = cur;
    cur = next;
  }
  return prev;
}

Complexity: Time O(n), Space O(n/k) recursion (O(1) iteratively)

Demo · Reverse Nodes in k-Groupplan · দিন ০৫৪LC 25
নোট · ফাঁকা

প্রবলেম

  • Reverse Linked Listplan · দিন ০০২🔥 Must-doLC 206
    (the template — you should be able to write it with eyes closed)

    Statement: Given the head of a singly linked list, reverse the list and return the new head.
    Example: [1,2,3,4,5][5,4,3,2,1] | ⚡ n ≤ 5000

    নোট · ফাঁকা
  • Reorder Listplan · দিন ০৫৩🔥 Must-doLC 143
    (middle + reverse + merge — three patterns combined)

    Statement: Given a singly linked list L0 → L1 → … → Ln-1 → Ln, reorder it in place to L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → ….
    Example: [1,2,3,4][1,4,2,3] | ⚡ n ≤ 5×10⁴

    নোট · ফাঁকা