[LeetCode] Merge Two Sorted Lists

Source: Internet
Author: User

[LeetCode] Merge Two Sorted Lists

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.

Solution:

This question is the easiest question for leetcode. One tips is to apply for a header node at the beginning and then delete it after merging. This makes the code clearer. The original space is used to accelerate the efficiency. The leetcode takes only 13 ms to run. Talk is cheap, show you the cade:

 

/*** 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) {ListNode * head = new ListNode (0); ListNode * p = head; // point to the last element of the fusion while (l1! = NULL & l2! = NULL) {if (l1-> val
 
  
Val) {p-> next = l1; p = l1; l1 = l1-> next;} else {p-> next = l2; p = l2; l2 = l2-> next;} while (l1! = NULL) {p-> next = l1; p = l1; l1 = l1-> next;} while (l2! = NULL) {p-> next = l2; p = l2; l2 = l2-> next;} p-> next = NULL; p = head; head = head-> next; delete p; return head ;}};
 


 

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.