您的位置:首页 > 其它

[leetcode Merge Two Sorted Lists]week 15

2017-07-07 02:02 316 查看
一、题目

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

二、代码

class Solution {

public:

   ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {

       ListNode* head=new ListNode(0);

                   ListNode*p=head;

                   while(l1!=NULL || l2!=NULL)

                   {

                            if(l1==NULL)

                            {

                                     p->next=l2;

                                     l2=l2->next;

                            }

                            elseif (l2==NULL)

                            {

                                     p->next=l1;

                                     l1=l1->next;

                            }

                            else

                            {

                                     if(l1->val < l2->val)

                                     {

                                               p->next=l1;

                                               l1=l1->next;

                                     }

                                     else

                                     {

                                               p->next=l2;

                                               l2=l2->next;                       

                                     }

                            }

                            p=p->next;

                   }

                   returnhead->next;

    }

};

三、思路
两个链表两个指针的val比对将新链表指针指向较小的节点。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: