Leetcode 21. Merge Sorted Lists

Source: Internet
Author: User

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 key to solve the problem is defining a fake head. Then compare the first elements from each list. Add the smaller one to the merged list. Finally, when one of them was empty, simply append it to the merged list, since it was already sorted.

Who put who in the small.

Java Code:

/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode mergetwolists (listnode L1, ListNode L2) {ListNode Fakehead=NewListNode (0); ListNode P=Fakehead; ListNode P1= L1, p2 =L2;  while(p1!=NULL&& P2! =NULL) {           if(P1.val <=p2.val) {P.next=P1; P1=P1.next; }Else{P.next=P2; P2=P2.next; } P=P.next; }        if(P1! =NULL) {P.next=P1; }        if(P2! =NULL) {P.next=P2; }        returnFakehead.next; }}

20160601:

/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode mergetwolists (listnode L1, ListNode L2) {ListNode dummy=NewListNode (0); ListNode cur=dummy;  while(L1! =NULL&& L2! =NULL) {            if(L1.val <=l2.val) {Cur.next=L1; L1=L1.next; } Else{Cur.next=L2; L2=L2.next; } cur=Cur.next; }        if(L1! =NULL) {Cur.next=L1; }        if(L2! =NULL) {Cur.next=L2; }        returnDummy.next; }}

Reference:

1. http://www.programcreek.com/2012/12/leetcode-merge-two-sorted-lists-java/

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.