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

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

    Here is the code on how to merge two sorted linked lists headA and headB:

    Node* MergeLists1(Node *headA, Node* headB)
    {
        Node *p = headA;
        Node *q = headB;
        Node *result = NULL; 
        Node *pp = NULL;
        Node *qq = NULL;
        Node *head = NULL;
        int value1 = 0;
        int value2 = 0;
        if((headA == NULL) && (headB == NULL))
        {
            return NULL;
        }
        if(headA==NULL)
        {
            return headB;
        }
        else if(headB==NULL)
        {
            return headA;
        }
        else
        {
            while((p != NULL) || (q != NULL))
            {
                if((p != NULL) && (q != NULL))
                {
                    int value1 = p->data;
                    int value2 = q->data;
                    if(value1 <= value2)
                    {
                        pp = p->next;
                        p->next = NULL;
                        if(result == NULL)
                        {
                            head = result = p;
                        }
                        else
                        {
                            result->next = p;
                            result = p;
                        }
                        p = pp;
                    }
                    else
                    {
                        qq = q->next;
                        q->next = NULL;
                        if(result == NULL)
                        {
                            head = result = q;
                        }
                        else
                        {
                            result->next = q;
                            result = q;
                        }
                        q = qq;
                    }
                }
                else
                {
                    if(p != NULL)
                    {
                        pp = p->next;
                        p->next = NULL;
                        result->next = p;
                        result = p;
                        p = pp;
                    }
                    if(q != NULL)
                    {
                        qq = q->next;
                        q->next = NULL;
                        result->next = q;
                        result = q;
                        q = qq;
                    }
                }
            }
        }
        return head;
    }
    

提交回复
热议问题