LeetCode 21 合并两个有序链表

第一次在python里用到链表这个数据结构,和cpp里很像,但还是要借用cpp中指针的概念。题目的重点是合并两个链表的过程。
非递归的答案:

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
class ListNode:
def __init__(self, x):
self.val = x
self.next = None

class Solution:
def mergeTwoLists(self, l1, l2):
newList = ListNode(-1)
if l1 is None and l2 is None:
return None

pre = newList
while l1 and l2:
if l1.val > l2.val:
pre.next = l2
l2 = l2.next
else:
pre.next = l1
l1 = l1.next
pre = pre.next
if l1 is not None:
pre.next = l1
if l2 is not None:
pre.next = l2
return newList.next

如果把第一个判断条件的and改为or会有一个测试用例无法通过:

Testcase

[]
[0]

Answer

[]

Expected Answer

[0]