Naive two pointer O(n+m) java


  • 0
    M
    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode answer = null;
            ListNode answerHead = null;
            if(l1 == null){
                return l2;
            }
            if(l2 == null){
                return l1;
            }
            ListNode ptr1 = l1;
            ListNode ptr2 = l2;
            
            while(ptr1!=null && ptr2!=null){
                
                if(ptr1.val < ptr2.val){
                    if(answer == null){
                        answer = new ListNode(ptr1.val);
                        answerHead = answer;
                    }
                    else{
                        answer.next = new ListNode(ptr1.val);
                        answer = answer.next;
                    }
                    ptr1 = ptr1.next;
                }
                else
                {
                    if(answer == null){
                        answer = new ListNode(ptr2.val);
                        answerHead = answer;
                        
                    }
                    else{
                        answer.next = new ListNode(ptr2.val);
                        answer = answer.next;
                    }
                    ptr2 = ptr2.next;
                }
            }
            
            ListNode runner = (ptr1==null)?ptr2:ptr1;
            while(runner != null){
                answer.next = new ListNode(runner.val);
                runner = runner.next;
                answer = answer.next;
            }
            return answerHead;
        }
    }
    

Log in to reply
 

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