7、 Merge Two Sorted Lists

版权声明:转载需转载声明 https://blog.csdn.net/qq_32285693/article/details/84193301

                                                                    Merge Two Sorted Lists

Descriptioin:

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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) 
    {
        //创建一个新的节点,并创建一个指针指向该节点
        ListNode* resultList = new ListNode(-1), *cur = resultList; 
        
        while(l1&&l2)  // 两个节点同时为真
        {
            if(l1->val < l2->val)
            {
                cur->next = l1;
                l1=l1->next;
            }
            else
            {
               
                cur->next = l2; 
                l2=l2->next;
            }
            cur = cur->next;
        }
        cur->next = l1?l1:l2;    // 那个为真,将剩下的连接到结果链表中
        
        return resultList->next;

猜你喜欢

转载自blog.csdn.net/qq_32285693/article/details/84193301