非商业,LeetCode链接附上:
https://leetcode-cn.com/problems/merge-two-sorted-lists/
进入正题。
题目:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
代码实现:
//节点
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode head = dummy;
while (l1 != null && l2 != null) {
if(l1.val <= l2.val) {
head.next = l1;
l1 = l1.next;
} else {
head.next = l2;
l2 = l2.next;
}
head = head.next;
}
head.next = l1 == null? l2 : l1;
return dummy.next;
}
//时间复杂度O(m+n),空间复杂度O(1)
分析:
设点一个“哨兵节点”,简化算法的实现。
两个链表都是升序的,可以直接通过比较和移动依次找到两个链表中的最小值。
--End
原文:https://www.cnblogs.com/heibingtai/p/14027327.html