add solution of lab 5
This commit is contained in:
@@ -15,6 +15,51 @@ public:
|
||||
// this function returns a pointer pointing to the head node of the merged list.
|
||||
template <class T>
|
||||
Node<T>* mergeLists(Node<T>* head_A, Node<T>* head_B) {
|
||||
// If one list is empty, return the other
|
||||
if (!head_A) return head_B;
|
||||
if (!head_B) return head_A;
|
||||
|
||||
// Decide the new head by comparing the first elements
|
||||
Node<T>* head = nullptr;
|
||||
Node<T>* tail = nullptr;
|
||||
|
||||
// Pick whichever head is smaller as the new head
|
||||
if (head_A->value < head_B->value) {
|
||||
head = head_A;
|
||||
head_A = head_A->next;
|
||||
} else {
|
||||
head = head_B;
|
||||
head_B = head_B->next;
|
||||
}
|
||||
// At this point, 'head' is the first node of the merged list
|
||||
head->prev = nullptr; // new head has no previous
|
||||
tail = head;
|
||||
|
||||
// Continue merging while both lists have nodes
|
||||
while (head_A && head_B) {
|
||||
if (head_A->value < head_B->value) {
|
||||
tail->next = head_A;
|
||||
head_A->prev = tail;
|
||||
tail = tail->next;
|
||||
head_A = head_A->next;
|
||||
} else {
|
||||
tail->next = head_B;
|
||||
head_B->prev = tail;
|
||||
tail = tail->next;
|
||||
head_B = head_B->next;
|
||||
}
|
||||
}
|
||||
|
||||
// Append any remaining nodes from A or B
|
||||
if (head_A) {
|
||||
tail->next = head_A;
|
||||
head_A->prev = tail;
|
||||
} else if (head_B) {
|
||||
tail->next = head_B;
|
||||
head_B->prev = tail;
|
||||
}
|
||||
|
||||
return head;
|
||||
}
|
||||
|
||||
int main() {
|
||||
|
||||
Reference in New Issue
Block a user