# Merge Sorted Linked List -Leetcode-Amazon Interview Question

1. Problem solving attitude and you must know what you are doing !
`/** * 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;             }};`

--

--

--

## More from 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

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

## 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