Interview Question: Merge two sorted singly linked lists without creating new nodes

后端 未结 26 2983
有刺的猬
有刺的猬 2020-12-02 04:09

This is a programming question asked during a written test for an interview. \"You have two singly linked lists that are already sorted, you have to merge them and return a

26条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-02 04:39

    Simple code in javascript to merge two linked list inplace.

    function mergeLists(l1, l2) {
        let head = new ListNode(0); //dummy
        let curr = head;
        while(l1 && l2) {
            if(l2.val >= l1.val) {
                curr.next = l1;
                l1 = l1.next;
            } else {
                curr.next = l2;
                l2=l2.next
            }
            curr = curr.next;
        }
        if(!l1){
            curr.next=l2;
        }
        if(!l2){
            curr.next=l1;
        } 
        return head.next;
    }
    

提交回复
热议问题