21. Merge Two Sorted Lists

来源:互联网 发布:js array indexof ie5 编辑:程序博客网 时间:2024/05/21 22:49

题目:Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

比较大小,谁小就先存储谁,不开辟新的空间。(直接两链表相连)


代码:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {    struct ListNode* l1node=l1;    struct ListNode* l2node=l2;    struct ListNode* pre=l2;        if( !l1 && !l2 ) return NULL;    else if( !l1) return l2;    else if( !l2) return l1;    else     {        while(l1node != NULL && l2node!=NULL)        {                int p=l1node->val;                int q=l2node->val;                if(p>q)                {                    pre=l2node;                    l2node=l2node->next;                }                else // p<q的情况                {                    //保存l1的下一个节点                    struct ListNode* savel1=l1node->next;                                        if(l2node==l2) //当小于l2的第一个节点时                    {                        l1node->next=l2node;                        pre=l1node;                                                l2node=pre->next;                        l2=l1node;                    }                    else                    {                        pre->next=l1node;                        pre=l1node;                                                l1node->next=l2node;                                                l2node=pre->next;                    }                    l1node=savel1;                }        }                    //l1还需要接在l2的后面            while(!l1node==NULL)            {                pre->next=l1node;                pre=l1node;                l1node=l1node->next;            }                    return l2;    }}

0 0
原创粉丝点击