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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
two pointer idea.
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy=ListNode(0)
cur=dummy
while l1 and l2:
if l1.val<l2.val:
cur.next=l1
l1=l1.next
else:
cur.next=l2
l2=l2.next
cur=cur.next
if l1:
cur.next=l1
if l2:
cur.next=l2
return dummy.next
本文介绍了一种使用双指针技巧来合并两个已排序链表的方法,并提供了完整的Python实现代码。该方法通过比较两个链表节点的值,将较小值的节点依次连接到新的链表中,最终返回合并后的有序链表。
1477

被折叠的 条评论
为什么被折叠?



