From c98b0be934f59ee9d6af407c24600a432cdc23e8 Mon Sep 17 00:00:00 2001 From: Shubham Raj <162688467+er-shubham-raj@users.noreply.github.com> Date: Sun, 26 Oct 2025 19:47:30 +0530 Subject: [PATCH] Implement merge of two sorted linked lists --- Merge Two Sorted Lists.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Merge Two Sorted Lists.cpp diff --git a/Merge Two Sorted Lists.cpp b/Merge Two Sorted Lists.cpp new file mode 100644 index 00000000..677a9444 --- /dev/null +++ b/Merge Two Sorted Lists.cpp @@ -0,0 +1,38 @@ +/** + * 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: + ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { + ListNode* t1 = list1; + ListNode* t2 = list2; + ListNode* dummyNode = new ListNode(-1); + ListNode* temp = dummyNode; + + while(t1 != NULL && t2 != NULL){ + if(t1 -> val < t2 -> val){ + temp->next = t1; + temp = t1; + t1 = t1->next; + } + else{ + temp->next = t2; + temp = t2; + t2 = t2->next; + + } + } + if(t1) temp->next =t1; + else{ + temp->next = t2; + } + return dummyNode->next; + } +};