链表:21. 合并两个有序链表 - 力扣(LeetCode)
无脑写,有点不优雅
1 # Definition for singly-linked list. 2 # class ListNode(object): 3 # def __init__(self, val=0, next=None): 4 # self.val = val 5 # self.next = next 6 class Solution(object): 7 def mergeTwoLists(self, list1, list2): 8 """ 9 :type list1: Optional[ListNode] 10 :type list2: Optional[ListNode] 11 :rtype: Optional[ListNode] 12 """ 13 pA = list1 14 pB = list2 15 if list1 == None and list2 == None: 16 return None 17 if list1 == None: 18 return list2 19 if list2 == None: 20 return list1 21 if pA.val <= pB.val: 22 resNode = pA 23 pA = pA.next 24 resNode.next = None 25 else: 26 resNode = pB 27 pB = pB.next 28 resNode.next = None 29 currNode = resNode 30 while pA and pB: 31 if pA.val <= pB.val: 32 currNode.next = pA 33 currNode = pA 34 pA = pA.next 35 currNode.next = None 36 else: 37 currNode.next = pB 38 currNode = pB 39 pB = pB.next 40 currNode.next = None 41 if pA == None: 42 currNode.next = pB 43 else: 44 currNode.next = pA 45 return resNode 46 47 48