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