解题思路
注意是有序链表
Java代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode prehead = new ListNode(-1);
ListNode prev = prehead;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
prev.next = l1;
l1 = l1.next;
} else {
prev.next = l2;
l2 = l2.next;
}
prev = prev.next;
}
// 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
prev.next = l1 == null ? l2 : l1;
return prehead.next;
}
}
python 代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
tem = ListNode(-1)
p = tem
while l1 and l2:
if l1.val < l2.val:
p.next = ListNode(l1.val)
l1 = l1.next
else:
p.next = ListNode(l2.val)
l2 = l2.next
p = p.next
if not l1:
p.next = l2
if not l2:
p.next = l1
return tem.next
if __name__ == '__main__':
s = Solution()
res = s.mergeTwoLists(1->2->4, 1->3->4)
print(res) # 1->1->2->3->4->4