My java solution


  • 0
    N
    public class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if(l1==null && l2==null) return null;
            if(l1==null) return l2;
            if(l2==null) return l1;
            ListNode list1 = l1;
            ListNode list2 = l2;
            int firstElement = 0;
            if(list1.val>list2.val){
                firstElement = list2.val;
                list2 = list2.next;
            }
            else{
                firstElement = list1.val;
                list1 = list1.next;
            }
            ListNode mergedList = new ListNode(firstElement);
            mergedList.next=null;
            ListNode newHead = mergedList;
            while(list1!=null && list2!=null){
               if(list1.val<list2.val){
                   ListNode insertElem = new ListNode(list1.val);
                   mergedList.next = insertElem;
                   mergedList = mergedList.next;
                   list1 = list1.next;
               } 
               else{
                   ListNode insertElem = new ListNode(list2.val);
                   mergedList.next = insertElem;
                   mergedList = mergedList.next;
                   list2 = list2.next;
               }
            }
            if(list1==null && list2!=null){
               mergedList.next = list2; 
               
            }
            else if(list1!=null && list2==null) {
                mergedList.next= list1;
            }
            else {}
            return newHead;
        }
    }

Log in to reply
 

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