LeetCode_Merge Two Sorted Lists,mergeksortedlists

來源:互聯網
上載者:User

LeetCode_Merge Two Sorted Lists,mergeksortedlists
一.題目Merge Two Sorted Lists  Total Accepted: 63974 Total Submissions: 196044My Submissions

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.

Show TagsHave you met this question in a real interview?  Yes No

Discuss






二.解題技巧    這道題就是將兩個已排序的列表的元素進行比較,當某一個列表的元素比較小的話,就將其加入到輸出資料行表中,並將該列表的指標指向列表的下一個元素。這道題是比較簡單的,但是有一個邊界條件要注意,就是兩個列表可能會出現為空白的情況,如果l1為空白時,可以直接將l2進行返回;如果l2為空白時,可以直接將l1返回,這樣可以減少很多計算量。

三.實現代碼
#include <iostream>/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode(int x) : val(x), next(NULL) {}* };*/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 Head(0);        ListNode *Pre = &Head;        while(l1 && l2)        {            if (l1->val < l2->val)            {                Pre->next = l1;                l1 = l1->next;                Pre = Pre->next;            }            else            {                Pre->next = l2;                l2 = l2->next;                Pre = Pre->next;            }        }        while (l1)        {            Pre->next = l1;            l1 = l1->next;            Pre = Pre->next;        }        while(l2)        {            Pre->next = l2;            l2 = l2->next;            Pre = Pre->next;        }        return Head.next;    }};




四.體會   這道題主要考察的就是邊界條件,主要就是處理鏈表為空白的情況,也就是,如果l1為空白,就返回l2,如果l2為空白,就直接返回l1。簡單的題要考慮充分啊。


著作權,歡迎轉載,轉載請註明出處,謝謝




著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.