21. Merge Two Sorted Lists

时间:2023-03-08 22:47:38

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

代码如下:

 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null&&l2==null)
return null;
if(l1==null&&l2!=null)
return l2;
if(l1!=null&&l2==null)
return l1; ListNode head=l1.val<=l2.val?l1:l2;
ListNode p=head;
if(head==l1)
l1=l1.next;
else if(head==l2)
l2=l2.next; while(l1!=null&&l2!=null)
{
head.next=l1.val<=l2.val?l1:l2;
if(head.next==l1)
l1=l1.next;
else if(head.next==l2)
l2=l2.next;
head=head.next;
} if(l1==null&&l2==null)
head.next=null;
if(l2!=null)
head.next=l2;
if(l1!=null)
head.next=l1; return p;
}
}