logo头像
Snippet 博客主题

【Leetcode 21】Merge Two Sorted Lists

难度: 简单(Easy)

题目:

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.

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(None)
p = head

while l1!=None and l2!=None:
p.next = l1
if l1.val < l2.val:
p = p.next
l1 = l1.next
else:
p.next = l2
p = p.next
l2 = l2.next

if l1 != None:
p.next = l1
if l2 != None:
p.next = l2

return head.next

评论系统未开启,无法评论!