/**
* 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) {
// Start typing your Java solution below
// DO NOT write main() function
if(l1==null){
return l2;
}else if(l2==null){
return l1;
}
ListNode p1=l1;
ListNode p2=l2;
ListNode head=null;
if(p1.val<p2.val){
head=p1;
p1=p1.next;
}else{
head=p2;
p2=p2.next;
}
ListNode cur =head;
while(p1!=null&&p2!=null){
if(p1.val<p2.val){
cur.next=p1;
p1=p1.next;
}else{
cur.next=p2;
p2=p2.next;
}
cur=cur.next;
}
if(p1==null){
cur.next=p2;
}
if(p2==null){
cur.next=p1;
}
return head;
}
}
Merge Two Sorted Lists
最新推荐文章于 2022-10-05 16:58:24 发布