Simple Java AC Solution


  • 0
    S
    public class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if(l1==null||l2==null) return l2==null?l1:l2;
            ListNode head=null,cur=null,h1=l1,h2=l2;
            while(h1!=null&&h2!=null){
                    ListNode next=h2;
                    if(h1.val<h2.val){
                       next=h1;
                       h1=h1.next;
                    } else {
                        h2=h2.next;
                    }
                    if(head==null){
                        head=next;
                        cur=head;
                    } else {
                        cur.next=next;
                        cur=cur.next;
                    }
                }
            cur.next = h1!=null?h1:h2;
            return head;
            
        }
    }
    

Log in to reply
 

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