Skip to content

Instantly share code, notes, and snippets.

@yashgyy
Created September 5, 2024 10:10
Show Gist options
  • Save yashgyy/195569cee74c15c000b8f1c81a2c3608 to your computer and use it in GitHub Desktop.
Save yashgyy/195569cee74c15c000b8f1c81a2c3608 to your computer and use it in GitHub Desktop.
Sorted LL
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
struct ListNode* header = NULL;
struct ListNode* head = NULL;
void newNode(int data) {
if (header == NULL) {
header = new ListNode(data);
head = header;
} else {
struct ListNode* temp;
temp = new ListNode(data);
header->next = temp;
header = header->next;
}
}
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
while (list1 && list2) {
if (list1->val < list2->val) {
newNode(list1->val);
list1 = list1->next;
} else {
newNode(list2->val);
list2 = list2->next;
}
}
if (list1) {
while (list1) {
newNode(list1->val);
list1 = list1->next;
}
} else {
while (list2) {
newNode(list2->val);
list2 = list2->next;
}
}
return head;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment