Skip to content

1669. Merge In Between Linked Lists 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
    ListNode* nodeBeforeA = list1;
    for (int i = 0; i < a - 1; ++i)
      nodeBeforeA = nodeBeforeA->next;

    ListNode* nodeB = nodeBeforeA->next;
    for (int i = 0; i < b - a; ++i)
      nodeB = nodeB->next;

    nodeBeforeA->next = list2;
    ListNode* lastNodeInList2 = list2;

    while (lastNodeInList2->next != nullptr)
      lastNodeInList2 = lastNodeInList2->next;

    lastNodeInList2->next = nodeB->next;
    nodeB->next = nullptr;
    return list1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
    ListNode nodeBeforeA = list1;
    for (int i = 0; i < a - 1; ++i)
      nodeBeforeA = nodeBeforeA.next;

    ListNode nodeB = nodeBeforeA.next;
    for (int i = 0; i < b - a; ++i)
      nodeB = nodeB.next;

    nodeBeforeA.next = list2;
    ListNode lastNodeInList2 = list2;

    while (lastNodeInList2.next != null)
      lastNodeInList2 = lastNodeInList2.next;

    lastNodeInList2.next = nodeB.next;
    nodeB.next = null;
    return list1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
  def mergeInBetween(
      self,
      list1: ListNode,
      a: int,
      b: int,
      list2: ListNode,
  ) -> ListNode:
    nodeBeforeA = list1
    for i in range(a - 1):
      nodeBeforeA = nodeBeforeA.next

    nodeB = nodeBeforeA.next
    for i in range(b - a):
      nodeB = nodeB.next

    nodeBeforeA.next = list2
    lastNodeInList2 = list2

    while lastNodeInList2.next:
      lastNodeInList2 = lastNodeInList2.next

    lastNodeInList2.next = nodeB.next
    nodeB.next = None
    return list1