My 8ms C++ iterative answer


  • 0
    L
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        // bounday situations
        if(!l1&&!l2) return l1;
        if(!l1||!l2) return (l1==nullptr?l2:l1);
        //general situations
         ListNode* pre;
         ListNode* res;
         //initialize the pre pointer
         if(l1->val<l2->val){
             pre = l1;
             l1 = l1->next;
         }else{
             pre= l2;
             l2 = l2->next;
         }
         //record head address
         res = pre;
         
         //sort, merge
         while(l1!=nullptr || l2!=nullptr){
             if(l2==nullptr&&l1!=nullptr){
                 while(l1!=nullptr){
                     pre->next = l1;
                     pre= pre->next;
                     l1 = l1->next;
                 }
             
                }else if(l1==nullptr &&l2!=nullptr){
                while(l2!=nullptr){
                     pre->next = l2;
                     pre= pre->next;
                     l2 = l2->next;
                 }
                
                }else{
                    if(l1->val < l2->val){
                         pre->next =l1;
                         pre= pre->next;
                         l1 = l1->next;
                     }
                     else{
                         pre->next = l2;
                         pre= pre->next;
                         l2=l2->next;
                     }
                }
        }   
        return res;
    }

  • 0
    Z

    //My solotion 0 is null

    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if (l1==0) return l2;
        if (l2==0) return l1;
        ListNode* pre = 0;
        ListNode* head = 0;
    	while (l1!=0 && l2!=0){
        	if (l1->val < l2->val){	
        		if (pre!=0){
        			pre->next=l1;	
        		}else{
        			head = l1;
        		}
        		pre=l1;
        		l1=l1->next;
        	}else{
        		
        		if (pre!=0){
        			pre->next=l2;
        		}else{
        			head=l2;
        		}
        		pre=l2;
        		l2=l2->next;
        	}
        }
        
        if (l1 == 0){
        	pre->next = l2;
        }
    
        if (l2 == 0){
        	pre->next=l1;
        }
    	return head;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.