leetcode-21 Merge Sorted Lists

Source: Internet
Author: User



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

Problem Analysis:

The algorithm itself is not difficult, comparing the values of two nodes of the linked list, whichever is smaller, assigns the result

The result of the method is to return the head pointer of the result linked list, so it should be saved with the pointer, and if set result is null, you will need to wait for L1 or L2 to result assignment to continue defining result.next, too cumbersome, so emulate the head node in C + + , define a new ListNode (0), then the head node is its Result.next;

Method Two is implemented by recursive method;

Code:

Class ListNode {     int val;     ListNode Next;     ListNode (int x) {val = x;}} public class Solution {public    ListNode mergetwolists (listnode L1, ListNode L2) {ListNode result = new ListNode (0); ListNode temp = Result;while ((L1! = null) && (L2! = null)) {if (L1.val <= l2.val) {temp.next = L1;L1 = L1.next;} else {temp.next = L2;L2 = L2.next;} temp = Temp.next;} if (L1! = null) Temp.next = L1;IF (L2! = null) Temp.next = L2;        return result.next;}    }


Method Two:

public class Solution {public    ListNode mergetwolists (listnode L1, ListNode L2) {    //Note The return value is not mistaken, this actually corresponds to the last related processing of the previous method    if (L1 = = null)  return L2;    if (L2 = = null)  return L1;        ListNode result = null;        if (l1.val <= l2.val)    {    result = L1;    Result.next = mergetwolists (L1.next, L2);    }    else        {        result = L2;result.next = mergetwolists (L1, L2.next);        }        return result;}    }


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.