"Leetcode" 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.

Answer

Note the use of false head nodes, the code is as follows:

/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * Next = Null            *} *} */public class Solution {public ListNode mergetwolists (listnode L1, ListNode L2) {if (l1==null) {        return L2;        } if (l2==null) {return L1;        } ListNode Mergehead=null;            if (l1.val<l2.val) {mergehead=l1;         L1=l1.next;  Mergehead.next=null;            Can not be, then the node will update}else{MERGEHEAD=L2;          L2=l2.next;        Mergehead.next=null;        } ListNode Cur=mergehead;                while (L1!=null&&l2!=null) {if (l1.val<l2.val) {cur.next=l1;                L1=l1.next;             Cur=cur.next;            Cur.next=null;                }else{Cur.next=l2;                L2=l2.next;             Cur=cur.next;        Cur.next=null;    }} if (L1!=null) {cur.next=l1;        }else if (l2!=null) {cur.next=l2;    } return mergehead; }}//uses a simplified version of the false head node public class Solution{public ListNode mergetwolists (listnode l1,listnode L2) {ListNode p1=l1; ListNode P2=l2;  ListNode fakehead=new ListNode (-1); Introduce a false head node ListNode p=fakehead;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;} return fakehead.next;}}

---EOF---


"Leetcode" 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.