title: 合并两个排序的链表 date: 2019-08-21T11:00:41+08:00 draft: false categories: offer
public ListNode Merge(ListNode list1, ListNode list2) {
ListNode head = new ListNode(-1);
ListNode cursor = head;
while (list1 != null || list2 != null) {
if (list1 == null) {
while (list2 != null) {
cursor.next = list2;
cursor = cursor.next;
list2 = list2.next;
}
continue;
}
if (list2 == null) {
while (list1 != null) {
cursor.next = list1;
cursor = cursor.next;
list1 = list1.next;
}
continue;
}
if (list1.val < list2.val) {
cursor.next = list1;
cursor = cursor.next;
list1 = list1.next;
} else {
cursor.next = list2;
cursor = cursor.next;
list2 = list2.next;
}
}
return head.next;
}