标签:col solution nbsp init == list python实现 and main
1 # Definition for singly-linked list. 2 class ListNode: 3 def __init__(self, x): 4 self.val = x 5 self.next = None 6 7 8 class Solution: 9 def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 10 11 new = ListNode(‘head‘) 12 new_cur = new 13 while l1 is not None and l2 is not None: 14 if l1.val <= l2.val: 15 new_cur.next = l1 16 new_cur = new_cur.next 17 l1 = l1.next 18 else: 19 new_cur.next = l2 20 new_cur = new_cur.next 21 l2 = l2.next 22 23 if l1 is None: 24 new_cur.next = l2 25 else: 26 new_cur.next = l1 27 28 return new.next 29 30 31 def Init_node(s: str) -> ListNode: 32 s = s.split(‘->‘) 33 head_node = ListNode(‘head‘) 34 35 for i in s: 36 new_node = ListNode(int(i)) 37 cur_node = head_node 38 while cur_node.next is not None: 39 cur_node = cur_node.next 40 cur_node.next = new_node 41 42 return head_node.next 43 def show_node(node:ListNode): 44 while node is not None: 45 print(node.val,end=‘ ‘) 46 node = node.next 47 print(‘‘) 48 49 if __name__ == ‘__main__‘: 50 51 s1 = ‘1->2->4‘ 52 s2 = ‘1->3->4‘ 53 list_node_1 = Init_node(s1) 54 list_node_2 = Init_node(s2) 55 56 solu = Solution() 57 merge = solu.mergeTwoLists(list_node_1, list_node_2) 58 show_node(merge)
标签:col solution nbsp init == list python实现 and main
原文地址:https://www.cnblogs.com/jiangnanyanyuchen/p/12681128.html