মূল কনটেন্টে যান
🛰️
রিমোট DSA
প্যাটার্নটপিক 3 · Linked Lists

3.2 Dummy Node Technique

চিনবেন কীভাবে
insert/delete/merge where the head may change — create a dummy and return dummy.next, and the head special case disappears
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন

Demo: Merge Two Sorted ListsLC 21 (Easy — Amazon/Meta/Google High)

Statement (Demo): Given the heads of two sorted linked lists list1 and list2, merge them into one sorted list and return its head. Example: list1=[1,2,4], list2=[1,3,4][1,1,2,3,4,4] | ⚡ n,m ≤ 50

Approach: Walk a tail from the dummy; attach the smaller node of the two lists each time. When one list runs out, attach the rest of the other directly.

function mergeTwoLists(a, b) {
  const dummy = { next: null };
  let tail = dummy;
  while (a && b) {
    if (a.val <= b.val) {
      tail.next = a;
      a = a.next;
    } else {
      tail.next = b;
      b = b.next;
    }
    tail = tail.next;
  }
  tail.next = a || b;
  return dummy.next;
}

Complexity: Time O(m+n), Space O(1)

Demo · Merge Two Sorted Listsplan · দিন ০২৬LC 21
নোট · ফাঁকা

প্রবলেম

  • (recursion is elegant here too)

    Statement: Given the head of a linked list, swap every two adjacent nodes by changing pointers, not values.
    Example: [1,2,3,4][2,1,4,3] | ⚡ n ≤ 100

    নোট · ফাঁকা