165. Merge Sorted Lists "Lintcode by Java"

Source: Internet
Author: User
Tags lintcode

Description

Merge sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should is made by splicing together the nodes of the and lists in sorted order.

Example

Given 1->3->8->11->15->null , 2->null return 1->2->3->8->11->15->null .

Problem solving: A classic topic, the merger of ordered lists. The Lintcode list does not have a head pointer by default, but it can construct a list of lead nodes to store the results, and then remove the head node when returning. The code is as follows:

/*** Definition for ListNode * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * next = NULL; *     } * } */ Public classSolution {/**     * @paramL1:listnode L1 is the head of the linked list *@paramL2:listnode L2 is the head of the linked list *@return: ListNode head of linked list*/     PublicListNode mergetwolists (listnode L1, ListNode L2) {//Write your code hereListNode Nhead =NewListNode (0); ListNode Rear=Nhead;  while(L1! =NULL&& L2! =NULL){            if(L1.val <l2.val) {Rear.next=L1; L1=L1.next; }Else{Rear.next=L2; L2=L2.next; } Rear=Rear.next; Rear.next=NULL; }        if(L1! =NULL) {Rear.next=L1; }Else{Rear.next=L2; }        returnnhead.next;//Key}}

165. Merge Sorted Lists "Lintcode by Java"

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.