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

后端 未结 26 3030
有刺的猬
有刺的猬 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 04:16

    Node MergeLists(Node list1, Node list2) {
      if (list1 == null) return list2;
      if (list2 == null) return list1;
    
      if (list1.data < list2.data) {
        list1.next = MergeLists(list1.next, list2);
        return list1;
      } else {
        list2.next = MergeLists(list2.next, list1);
        return list2;
      }
    }
    

提交回复
热议问题