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

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

提交回复
热议问题