LeetCode Algorithms #21 <Merge Two Sorted Lists>

来源:互联网 发布:淘宝商品代理 编辑:程序博客网 时间:2024/06/14 12:04

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.

思路:

就和玩积木一样,这些基本的链表操作是没有任何难度的,小心些,不犯低级错误就可以一次ac。

解:

/** * 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)            return l2;        if(!l2 )            return l1;                    ListNode* newListHead = nullptr;        ListNode* newListTail = nullptr;                if(l1->val < l2->val)        {            newListHead = l1;            newListTail = newListHead;            l1 = l1->next;        }        else        {            newListHead = l2;            newListTail = newListHead;            l2 = l2->next;        }                while(true)        {            if(!l1)            {                newListTail->next = l2;                break;            }                        if(!l2)            {                newListTail->next = l1;                break;            }                        if(l1->val < l2->val)            {                newListTail->next = l1;                l1 = l1->next;                newListTail = newListTail->next;            }            else            {                newListTail->next = l2;                l2 = l2->next;                newListTail = newListTail->next;            }        }                return newListHead;    }};


0 0
原创粉丝点击