-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathMergeTwoSortedList.cpp
More file actions
95 lines (80 loc) · 2.13 KB
/
Copy pathMergeTwoSortedList.cpp
File metadata and controls
95 lines (80 loc) · 2.13 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <iostream>
using namespace std;
// Define a node for the linked list
struct Node {
int data;
Node* next;
Node(int val) {
data = val;
next = nullptr;
}
};
// Function to insert a new node at the end of the list
void insertAtEnd(Node*& head, int val) {
Node* newNode = new Node(val);
if (head == nullptr) { // if list is empty
head = newNode;
return;
}
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
// Function to print the linked list
void printList(Node* head) {
while (head != nullptr) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
// Function to merge two sorted linked lists
Node* mergeTwoSortedLists(Node* l1, Node* l2) {
// If any list is empty, return the other
if (!l1) return l2;
if (!l2) return l1;
// Create a dummy node to simplify handling of the head
Node* dummy = new Node(-1);
Node* tail = dummy;
// Traverse both lists and pick smaller elements
while (l1 && l2) {
if (l1->data <= l2->data) {
tail->next = l1;
l1 = l1->next;
} else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
// If any nodes remain in one list, connect them
if (l1) tail->next = l1;
if (l2) tail->next = l2;
// Return merged list (skip dummy)
return dummy->next;
}
int main() {
Node* list1 = nullptr;
Node* list2 = nullptr;
int n1, n2, val;
cout << "Enter number of elements in first sorted list: ";
cin >> n1;
cout << "Enter elements of first sorted list: ";
for (int i = 0; i < n1; i++) {
cin >> val;
insertAtEnd(list1, val);
}
cout << "Enter number of elements in second sorted list: ";
cin >> n2;
cout << "Enter elements of second sorted list: ";
for (int i = 0; i < n2; i++) {
cin >> val;
insertAtEnd(list2, val);
}
cout << "\nMerged Sorted List: ";
Node* mergedList = mergeTwoSortedLists(list1, list2);
printList(mergedList);
return 0;
}