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

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

    Node * merge_sort(Node *a, Node *b){
       Node *result = NULL;
       if(a ==  NULL)
          return b;
       else if(b == NULL)
          return a;
    
      /* For the first node, we would set the result to either a or b */
        if(a->data <= b->data){
           result = a;
        /* Result's next will point to smaller one in lists 
           starting at a->next  and b */
          result->next = merge_sort(a->next,b);
        }
        else {
          result = b;
         /*Result's next will point to smaller one in lists 
           starting at a and b->next */
           result->next = merge_sort(a,b->next);
        }
        return result;
     }
    

    Please refer to my blog post for http://www.algorithmsandme.com/2013/10/linked-list-merge-two-sorted-linked.html

提交回复
热议问题