題目描述:
輸入兩個單調遞增的鏈表,輸出兩個鏈表合成後的鏈表,當然我們需要合成後的鏈表滿足單調不減規則。
主要思想 :
public static ListNode Merge(ListNode list1, ListNode list2) {
ListNode head = null;
if (list1 == null && list2 == null)
return head;
if (list1.val <= list1.val) {
head = list1;
list1 = list1.next;
} else {
head = list2;
list2 = list2.next;
}
ListNode P = head;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
P.next = list1;
P = P.next;
list1 = list1.next;
} else {
P.next = list2;
P = P.next;
list2 = list2.next;
}
}
if (list1 != null) {
P.next = list1;
}
if (list2 != null) {
P.next = list2;
}
return head;
}
注意點:
- 判斷兩個鏈表均爲空時,返回null