题目描述: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 def mergeTwoLists(self, l1, l2): 2 if l1 == None: 3 return l2 4 elif l2 == None: 5 return l1 6 elif l1 == None and l2 == None: 7 return None 8 else: 9 p1 = l1 10 p2 = l2 11 if p1.val > p2.val: 12 l = p2 13 p = p2 14 p2 = p2.next 15 while p1 and p2: 16 if p1.val > p2.val: 17 p.next = p2 18 p = p2 19 p2 = p2.next 20 21 else: 22 p.next = p1 23 p = p1 24 p1 = p1.next 25 26 if p1: 27 while p1: 28 p.next = p1 29 p = p1 30 p1 = p1.next 31 return l 32 if p2: 33 while p2: 34 p.next = p2 35 p = p2 36 p2 = p2.next 37 return l 38 else: 39 l = p1 40 p = p1 41 p1 = p1.next 42 while p1 and p2: 43 if p1.val > p2.val: 44 p.next = p2 45 p = p2 46 p2 = p2.next 47 48 else: 49 p.next = p1 50 p = p1 51 p1 = p1.next 52 53 if p1: 54 while p1: 55 p.next = p1 56 p = p1 57 p1 = p1.next 58 return l 59 if p2: 60 while p2: 61 p.next = p2 62 p = p2 63 p2 = p2.next 64 return l
时间: 2024-10-01 03:27:57