Java [leetcode 21]Merge Two Sorted Lists

时间:2023-03-09 03:16:00
Java [leetcode 21]Merge Two Sorted Lists

题目描述:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

解题思路:

题目的意思是将两个有序链表合成一个有序链表。

逐个比较加入到新的链表即可。

代码如下:

public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode list = new ListNode(0);
ListNode tmp = list;
while (l1 != null || l2 != null) {
if (l1 == null) {
tmp.next = new ListNode(l2.val);
l2 = l2.next;
} else if (l2 == null) {
tmp.next = new ListNode(l1.val);
l1 = l1.next;
} else {
if (l1.val < l2.val) {
tmp.next = new ListNode(l1.val);
l1 = l1.next;
} else {
tmp.next = new ListNode(l2.val);
l2 = l2.next;
}
}
tmp = tmp.next;
}
return list.next;
}