[AlgoExpert] Merge Linked Lists

Merge Linked Lists

  • Time : O(n+m)
  • 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
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <vector>

using namespace std;

// This is an input class. Do not edit.
class LinkedList {
public:
int value;
LinkedList *next;

LinkedList(int value) {
this->value = value;
next = nullptr;
}
};

LinkedList *mergeLinkedLists(LinkedList *headOne, LinkedList *headTwo) {
LinkedList* dummy = new LinkedList(-1);
LinkedList* tail = dummy;
while(headOne and headTwo) {
if(headOne->value < headTwo->value) {
tail->next = headOne;
headOne = headOne->next;
} else {
tail->next = headTwo;
headTwo = headTwo->next;
}
tail = tail->next;
}
if(headOne) tail->next = headOne;
if(headTwo) tail->next = headTwo;
return dummy->next;
}


Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/merge-linked-lists/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.