/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
//迭代:时间复杂度O(n),空间复杂度0(1)
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null) return list2 ;
if(list2 == null) return list1 ;
ListNode l1 = list1 ;
ListNode l2 = list2 ;
ListNode home = new ListNode(Integer.MAX_VALUE) ;
ListNode cur = home ;
while(l1 != null && l2 != null) {
if(l1.val < l2.val) {
cur.next = l1 ;
cur = cur.next ;
l1 = l1.next ;
} else {
cur.next = l2 ;
cur = cur.next ;
l2 = l2.next ;
}
}
while(l1 != null) {
cur.next = l1 ;
cur = cur.next ;
l1 = l1.next ;
}
while(l2 != null) {
cur.next = l2 ;
cur = cur.next ;
l2 = l2.next ;
}
return home.next ;
}
}
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
//迭代:时间复杂度O(n),空间复杂度0(1)
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null) return list2 ;
if(list2 == null) return list1 ;
ListNode l1 = list1 ;
ListNode l2 = list2 ;
ListNode home = new ListNode(Integer.MAX_VALUE) ;
ListNode cur = home ;
while(l1 != null && l2 != null) {
if(l1.val < l2.val) {
cur.next = l1 ;
cur = cur.next ;
l1 = l1.next ;
} else {
cur.next = l2 ;
cur = cur.next ;
l2 = l2.next ;
}
}
while(l1 != null) {
cur.next = l1 ;
cur = cur.next ;
l1 = l1.next ;
}
while(l2 != null) {
cur.next = l2 ;
cur = cur.next ;
l2 = l2.next ;
}
return home.next ;
}
}