class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public ListNode Merge(ListNode list1, ListNode list2) {
if (list1 == null) return list2;
if (list2 == null) return list1;
ListNode newHead = null;
if (list1.val >= list2.val) {
newHead = new ListNode(list2.val);
list2 = list2.next;
} else {
newHead = new ListNode(list1.val);
list1 = list1.next;
}
ListNode cur = newHead;
while (list1 != null && list2 != null) {
if (list1.val >= list2.val) {
cur.next = new ListNode(list2.val);
list2 = list2.next;
cur = cur.next;
} else {
cur.next = new ListNode(list1.val);
list1 = list1.next;
cur = cur.next;
}
}
while (list1 != null) {
cur.next = new ListNode(list1.val);
list1 = list1.next;
cur = cur.next;
}
while (list2 != null) {
cur.next = new ListNode(list2.val);
list2 = list2.next;
cur = cur.next;
}
return newHead;
}
两个有序链表合并
最新推荐文章于 2021-03-20 21:35:03 发布