2刷
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null) return l2;
if(l2==null) return l1;
if(l1==null&&l2==null) return null;
ListNode head=new ListNode(0);
ListNode cur=head;
while(l1!=null&&l2!=null){
if(l1.val<l2.val){
cur.next=l1;
l1=l1.next;
cur=cur.next;
}
else if(l1.val>l2.val){
cur.next=l2;
l2=l2.next;
cur=cur.next;
}
else{//(l1.val==l2.val)
cur.next=l1;
l1=l1.next;
cur=cur.next;
cur.next=l2;
l2=l2.next;
cur=cur.next;
}
}
if(l1!=null){
cur.next=l1;
}
if(l2!=null){
cur.next=l2;
}
return head.next;
}
}
结果
复杂度
时间复杂度O(M+N)遍历两个链表
空间复杂度O(1)
1刷
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//有链表为空的情况
if(l1==null)
return l2;
if(l2==null)
return l1;
//存放头结点
ListNode tmp=null;
//运算中用的结点
ListNode head=null;
//标志是否第一个结点
int count=0;
while(l1!=null&&l2!=null){
//初始化head
if(count==0){
if(l1.val<=l2.val){
tmp=l1;
head=l1;
l1=l1.next;
}
else{
tmp=l2;
head=l2;
l2=l2.next;
}
count++;
}
else{
if(l1.val<=l2.val){
head.next=l1;
l1=l1.next;
head=head.next;
}
else{
head.next=l2;
l2=l2.next;
head=head.next;
}
}
}
if(l1!=null){
head.next=l1;
}
else if(l2!=null){
head.next=l2;
}
else{
head.next=null;
}
return tmp;
}
}