LeetCode,leetcodeoj

來源:互聯網
上載者:User

LeetCode,leetcodeoj

題目連結:Merge Two Sorted Lists

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.

這道題的要求是將兩個已經排好序的鏈表合并成1個有序鏈表。

這道題的思路比較簡單,主要就是考察鏈表的處理。這裡還是像Remove Nth Node From End of List一樣先在鏈表前面加頭,這樣可以免去對鏈表頭的特殊處理。接下來就是每次取兩個鏈表前面較小的元素,直到有鏈表到達結尾。最後再將沒有到達結尾的鏈表直接連結到合并的鏈表的後面,並返回合并後鏈表頭後面的節點指標即可。

時間複雜度:O(n)

空間複雜度:O(1)

 1 class Solution 2 { 3 public: 4     ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) 5     { 6         ListNode *h = new ListNode(0), *p = h; 7          8         while(l1 != NULL && l2 != NULL) 9         {10             if(l1 -> val < l2 -> val)11             {12                 p -> next = l1;13                 l1 = l1 -> next;14             }15             else16             {17                 p -> next = l2;18                 l2 = l2 -> next;19             }20             21             p = p -> next;22         }23         24         if(l1 != NULL)25             p -> next = l1;26         if(l2 != NULL)27             p -> next = l2;28         29         return h -> next;30     }31 };

轉載請說明出處:LeetCode --- 21. Merge Two Sorted Lists

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.