迭代
- python版本
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
c = dummy = ListNode(0)
while l1 and l2:
if l1.val<=l2.val:
c.next = l1
l1 = l1.next
else:
c.next =l2
l2 =l2.next
c =c.next
c.next = l1 if l1 is not None else l2
return dummy.next
- go版本
type ListNode struct {
Val int
Next *ListNode
}
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
l := &ListNode{Val: 0}
dummy:=l
for l1 != nil && l2 != nil {
if l1.Val <= l2.Val {
l.Next = l1
l1 = l1.Next
} else {
l.Next = l2
l2 = l2.Next
}
l = l.Next
}
if l1 !=nil{
l.Next=l1
}else{
l.Next=l2
}
return dummy.Next
}
网友评论