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

后端 未结 26 2684
有刺的猬
有刺的猬 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

    Recursion should not be needed to avoid allocating a new node:

    Node MergeLists(Node list1, Node list2) {
      if (list1 == null) return list2;
      if (list2 == null) return list1;
    
      Node head;
      if (list1.data < list2.data) {
        head = list1;
      } else {
        head = list2;
        list2 = list1;
        list1 = head;
      }
      while(list1.next != null) {
        if (list1.next.data > list2.data) {
          Node tmp = list1.next;
          list1.next = list2;
          list2 = tmp;
        }
        list1 = list1.next;
      } 
      list1.next = list2;
      return head;
    }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题