21. Merge Two Sorted Lists
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Constraints:
- The number of nodes in both lists is in the range [0, 50].
- -100 <= Node.val <= 100
- Both list1 and list2 are sorted in non-decreasing order.
Example
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
思路
将两个链表头节点相比较,依次遍历,谁小就尾插进结果节点
题解
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
// 存放结果
ListNode result = new ListNode(0, new ListNode());
// 存放结果头节点
ListNode temp = result;
// 两个链表只要有一个到头就结束
while (list1 != null && list2 != null) {
// 链表1当前节点比链表2大,那就把链表2当前节点续在结果节点后面
if (list1.val > list2.val) {
temp.next = new ListNode(list2.val, new ListNode());
// 遍历下一个节点
list2 = list2.next;
} else {
// 链表1小就把链表1续在结果节点后面
temp.next = new ListNode(list1.val, new ListNode());
list1 = list1.next;
}
// 结果节点往下移
temp = temp.next;
}
// 最后无非就是把先把链表1遍历完了,或者是先把链表2遍历完了,while就停止=
// 那这边就看当前哪个链表为null,那么另一个链表就还有值,把其续在结果节点后面
if (list1 == null)
temp.next = list2;
else
temp.next = list1;
return result.next;
}
标签:ListNode,21,list1,Two,Lists,list2,链表,next,节点
From: https://www.cnblogs.com/tanhaoo/p/17075666.html