[LeetCode]Merge Two Sorted Lists

来源:互联网 发布:淘宝试用成功怎么领取 编辑:程序博客网 时间:2024/05/23 13:54

题目: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.

合并有序链表。


class Solution{public:    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)    {        if(l1==NULL)            return l2;        if(l2==NULL)            return l1;        ListNode *p = l1->val<l2->val? l1:l2;        ListNode *q = l1->val<l2->val? l2:l1;        ListNode *cur = p;        while(cur->next!=NULL && q!=NULL )        {            if(q->val<=cur->next->val)            {                ListNode *tmp=q;                q=q->next;                tmp->next=cur->next;                cur->next=tmp;                cur=cur->next;            }            else            {                cur=cur->next;            }        }        if(q!=NULL)            cur->next=q;        return p;    }};


0 0