Merge Sorted Linked List -Leetcode-Amazon Interview Question

  1. Problem solving attitude and you must know what you are doing !
  2. Pointers, Linked List
/**
* 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* l1, ListNode* l2) {

if(!l1 && !l2){
return NULL;
}
else if(l1 && !l2){
return l1;
}
else if(!l1 && l2){
return l2;
}

ListNode * temp1 = l1;
ListNode * temp2 = l2;
ListNode * temp3 = NULL;
ListNode * head = NULL;

while(temp1 && temp2){

if(temp1->val <= temp2->val){
//initialize head if it is NULL
if(head == NULL){
head = temp1;
temp3 = head;
temp1 = temp1->next;
}
else{
temp3->next = temp1;
temp3 = temp3->next;
temp1 = temp1->next;
}
}
//list 1 value is greater than list2 value
else{
//initialize head if it is NULL
if(head == NULL){
head = temp2;
temp3 = head;
temp2 = temp2->next;
}
else{
temp3->next = temp2;
temp3 = temp3->next;
temp2 = temp2->next;
}

}
} //end of while
//if list1 still has elements
while(temp1){
temp3->next = temp1;
temp3= temp3->next;
temp1 = temp1->next;
}
//if list2 still has elements
while(temp2){
temp3->next = temp2;
temp3= temp3->next;
temp2 = temp2->next;
}

return head;

}
};

--

--

--

My real Twitter Id: https://twitter.com/Bogati2017 I tutor coding: M-F:4pm-8pm sat/sun: 7am-7pm for AP/undergrads reach me at email: bimalacal2022@gmail.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to save Allure Environment data of the Test run automatically

How to open an excel file with multiple sheets in Python?

Flutter Best Practices, Custom Fonts

Sonic Pi: Music & Magic

Know your systems failure modes

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Bimala Bogati

Bimala Bogati

My real Twitter Id: https://twitter.com/Bogati2017 I tutor coding: M-F:4pm-8pm sat/sun: 7am-7pm for AP/undergrads reach me at email: bimalacal2022@gmail.com

More from Medium

LeetCode: Palindrome Number

[LeetCode — 322] Coin Change

Find First And Last Position of Element in Sorted Array

How to start Leetcode grind

Binary tree