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

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

    First of all understand the mean of "without creating any new extra nodes", As I understand it does not mean that I can not have pointer(s) which points to an existing node(s).

    You can not achieve it without talking pointers to existing nodes, even if you use recursion to achieve the same, system will create pointers for you as call stacks. It is just like telling system to add pointers which you have avoided in your code.

    Simple function to achieve the same with taking extra pointers:

    typedef struct _LLNode{
        int             value;
        struct _LLNode* next;
    }LLNode;
    
    
    LLNode* CombineSortedLists(LLNode* a,LLNode* b){
        if(NULL == a){
            return b;
        }
        if(NULL == b){
            return a;
        }
        LLNode* root  = NULL;
        if(a->value < b->value){
            root = a;
            a = a->next;
        }
        else{
            root = b;
            b    = b->next;
        }
        LLNode* curr  = root;
        while(1){
            if(a->value < b->value){
                curr->next = a;
                curr = a;
                a=a->next;
                if(NULL == a){
                    curr->next = b;
                    break;
                }
            }
            else{
                curr->next = b;
                curr = b;
                b=b->next;
                if(NULL == b){
                    curr->next = a;
                    break;
                }
            }
        }
        return root;
    }
    

提交回复
热议问题