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

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

    Recursive way(variant of Stefan answer)

     MergeList(Node nodeA, Node nodeB ){
            if(nodeA==null){return nodeB};
            if(nodeB==null){return nodeA};
    
        if(nodeB.data

    Consider below linked list to visualize this

    2>4 list A 1>3 list B

    Almost same answer(non recursive) as Stefan but with little more comments/meaningful variable name. Also covered double linked list in comments if someone is interested

    Consider the example

    5->10->15>21 // List1

    2->3->6->20 //List2

    Node MergeLists(List list1, List list2) {
      if (list1 == null) return list2;
      if (list2 == null) return list1;
    
    if(list1.head.data>list2.head.data){
      listB =list2; // loop over this list as its head is smaller
      listA =list1;
    } else {
      listA =list2; // loop over this list
      listB =list1;
    }
    
    
    listB.currentNode=listB.head;
    listA.currentNode=listA.head;
    
    while(listB.currentNode!=null){
    
      if(listB.currentNode.data

提交回复
热议问题