From af930cfcfb8d96aa480aad575db0d29730b733e8 Mon Sep 17 00:00:00 2001 From: SACHIKANTA DAS <61788396+Sachikant786@users.noreply.github.com> Date: Sun, 9 Oct 2022 12:00:22 +0530 Subject: [PATCH] Create Merge Two Sorted Lists.CPP --- C++ BASIC COURSE/Merge Two Sorted Lists.CPP | 33 +++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++ BASIC COURSE/Merge Two Sorted Lists.CPP diff --git a/C++ BASIC COURSE/Merge Two Sorted Lists.CPP b/C++ BASIC COURSE/Merge Two Sorted Lists.CPP new file mode 100644 index 0000000..9f8b119 --- /dev/null +++ b/C++ BASIC COURSE/Merge Two Sorted Lists.CPP @@ -0,0 +1,33 @@ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) + { + // if list1 happen to be NULL + // we will simply return list2. + if(l1 == NULL) + { + return l2; + } + + // if list2 happen to be NULL + // we will simply return list1. + if(l2 == NULL) + { + return l1; + } + + // if value pointend by l1 pointer is less than equal to value pointed by l2 pointer + // we wall call recursively l1 -> next and whole l2 list. + if(l1 -> val <= l2 -> val) + { + l1 -> next = mergeTwoLists(l1 -> next, l2); + return l1; + } + // we will call recursive l1 whole list and l2 -> next + else + { + l2 -> next = mergeTwoLists(l1, l2 -> next); + return l2; + } + } +};