LeetCode 21:Merge Two Sorted Lists

来源:互联网 发布:nginx 域名指向目录 编辑:程序博客网 时间:2024/04/30 20:43

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.

将两个已排序的链表合并成一个新链表,新列表应该包含前两个链表的所有节点。


好这道题一开始卡了我好几个小时,在我千辛万苦终于写出来一个可以用的版本时,它告诉我超!时!了!嗯,于是我灵光一闪,花了5分钟写了另一个版本,于是通过了。。。为什么这么简单的方法我之前没想到啊魂淡!为什么突然又想出来了啊魂淡!

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; *//*class Solution {public:    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {        if(l1==NULL) return l2;        else if(l2==NULL) return l1;        else        {            ListNode *temp,*head;            temp=head;            while(l1->next&&l2->next)            {                if(l1->val>l2->val)                {                    head->next=l2;                    l2=l2->next;                }                else                {                    head->next=l1;                    l1=l1->next;                }                head=head->next;            }            if(!l1->next&&l2->next)            {                while(l2->next)                {                    if(l1->val>l2->val)                    {                        head->next=l2;                        l2=l2->next;                        head=head->next;                    }                    else                    {                        head->next=l1;                        l1->next=l2;                        break;                    }                }            }            else if(!l2->next&&l1->next)            {                while(l1->next)                {                    if(l2->val>l1->val)                    {                        head->next=l1;                        l1=l1->next;                        head=head->next;                    }                    else                    {                        head->next=l2;                        l2->next=l1;                        break;                    }                }            }            if(l1->val<l2->val)            {                head->next=l1;                l1->next=l2;            }            else            {                head->next=l2;                l2->next=l1;            }            return temp->next;        }    }};*/class Solution {public:    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {        ListNode* head=new ListNode(0);        ListNode* temp=head;        while(l1&&l2)        {            if(l1->val<l2->val)            {                head->next=l1;                l1=l1->next;            }            else            {                head->next=l2;                l2=l2->next;            }            head=head->next;        }        if(!l1) head->next=l2;        if(!l2) head->next=l1;        return temp->next;    }};


0 0
原创粉丝点击