LeetCode, leetcodeoj

Source: Internet
Author: User

LeetCode, leetcodeoj

Link: Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list shoshould be made by splicing together the nodes of the first two lists.

The requirement for this question is to combine two sorted linked lists into one ordered linked list.

The idea of this question is relatively simple. It mainly refers to the handling of linked lists. Add a header to the front of the linked List like removing Nth Node From End of List. This removes the need for special processing on the linked List header. The next step is to take the small elements in front of two linked lists each time until a linked list reaches the end. Finally, you can directly link the linked list that does not reach the end to the end of the merged linked list, and return the node pointer behind the merged linked list header.

Time Complexity: O (n)

Space complexity: 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 };

Reprinted please note the Source: LeetCode --- 21. Merge Two Sorted Lists

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.