Leetcode | #21 Merge Sorted Lists

Source: Internet
Author: User

Topic:

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

Ideas:

    • Set two head pointers, one pointer fixed, to return the last header, a pointer to organize the node order, traverse the two linked lists, each pointing to a small node
public class Mergetwosortedlists {public class ListNode {int val; ListNode Next; ListNode (int x) {val = x;    next = null;}} Public ListNode mergetwolists (listnode L1, ListNode L2) {        ListNode h1 = new ListNode (0), H2 = H1;while (L1!=null && Amp L2!=null) {if (L1.val < l2.val) {H1.next = L1;L1 = L1.next;} Else{h1.next = L2;l2 = L2.next;} H1 = H1.next;} if (L1 = = null) {h1.next = L2;} if (L2 = = null) {h1.next = L1;} return h2.next;}    }

    • There is also a more cock method, recursive, and the smallest node is selected each time, but the code is more concise
Recursive method, the head pointer points to the smallest node in two lists at a time, and then recursively public listnode mergetwolists (listnode L1, ListNode L2) {        if (L1 = null) return l2;if ( L2 = = null) return L1; ListNode h;if (L1.val < l2.val) {h = L1;h.next = Mergetwolists (L1.next, L2);} else{h = L2;h.next = mergetwolists (L1, l2.next);} return h;}


Leetcode | #21 Merge 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.