Java [Leetcode 21]merge-Sorted Lists

Source: Internet
Author: User

Title Description:

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.

Problem Solving Ideas:

The title means to synthesize an ordered list of two ordered linked lists.

Add to the new list by comparison.

The code is as follows:

public static ListNode mergetwolists (ListNode L1, ListNode L2) {ListNode list = new ListNode (0);  ListNode tmp = list;while (L1! = NULL | | L2! = NULL) {if (L1 = = null) {Tmp.next = new ListNode (l2.val); l2 = L2.next;} else if (L2 = = null) {Tmp.next = new ListNode (l1.val); l1 = L1.next;} else {if (L1.val < l2.val) {tmp.next = new ListNode (L1 . val); l1 = L1.next;} else {tmp.next = new ListNode (l2.val); l2 = L2.next;}} TMP = Tmp.next;} return list.next;}


Java [Leetcode 21]merge-Sorted Lists

Related Article

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.