- https://leetcode.com/problems/merge-two-sorted-lists/
- https://leetcode-cn.com/problems/merge-two-sorted-lists/
- 链表
每次选择两个链表头部较小的一个节点,然后剩下的节点和另外一个链表的元素继续merge.
子问题为去掉当前最小的元素,剩下的元素继续merge。
# pseudo code
if list1[0] < list2[0]:
list1[0] + merge(list1[1:], list2)
else:
list2[0] + merge(list1, list2[1:])
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
if l1 is None:
return l2
if l2 is None:
return l1
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
Go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
if l1.Val < l2.Val {
l1.Next = mergeTwoLists(l1.Next, l2)
return l1
}
l2.Next = mergeTwoLists(l2.Next, l1)
return l2
}
Go
func mergeTwoLists(l1, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
n := &ListNode{}
if l1.Val < l2.Val {
n.Val = l1.Val
n.Next = mergeTwoLists1(l1.Next, l2)
} else {
n.Val = l2.Val
n.Next = mergeTwoLists1(l1, l2.Next)
}
return n
}
l1 始终保存最小的元素的链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
if l1 and l2:
if l1.val > l2.val:
l1, l2 = l2, l1
l1.next = self.mergeTwoLists(l1.next, l2)
return l1 or l2
用一个指针保存当前的位置,每一次选出一个最小的元素,插入到当前的位置。
其实是用迭代改写Solution1的递归,思路一样。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
if l1 is None:
return l2
if l2 is None:
return l1
dummy = cur = ListNode(None)
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
cur.next = l1 if l1 else l2
return dummy.next
Go
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
dummy := &ListNode{}
cur := dummy
for l1 != nil && l2 != nil {
if l1.Val < l2.Val {
cur.Next = l1
l1 = l1.Next
} else {
cur.Next = l2
l2 = l2.Next
}
cur = cur.Next
}
if l1 != nil {
cur.Next = l1
} else {
cur.Next = l2
}
return dummy.Next
}