leetCode练题——21. Merge Two Sorted Lists(照搬大神做法)
1、题目
21. Merge Two Sorted Lists
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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
2、我的解答
1 # -*- coding: utf-8 -*- 2 # @Time : 2020/2/1 18:30 3 # @Author : SmartCat0929 4 # @Email : 1027699719@qq.com 5 # @Link : https://github.com/SmartCat0929 6 # @Site : 7 # @File : 21.Merge Two Sorted Lists.py 8 9 # Definition for singly-linked list. 10 class ListNode: 11 def __init__(self, x): 12 self.val = x 13 self.next = None 14 15 class Solution: 16 def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 17 head = l3 = ListNode(0) 18 while(l1 is not None and l2 is not None): 19 if l1.val <=l2.val: 20 l3.next = ListNode(l1.val) 21 l3 = l3.next 22 l1 = l1.next 23 else: 24 l3.next = ListNode(l2.val) 25 l3 = l3.next 26 l2 = l2.next 27 while l1: 28 l3.next = ListNode(l1.val) 29 l3 = l3.next 30 l1 = l1.next 31 while l2: 32 l3.next = ListNode(l2.val) 33 l3 = l3.next 34 l2 = l2.next 35 return head.next 36 37 h1 = ListNode(1) 38 h1.next = ListNode(2) 39 h1.next.next = ListNode(4) 40 41 h2 = ListNode(1) 42 h2.next = ListNode(3) 43 h2.next.next = ListNode(4) 44 45 h = Solution().mergeTwoLists(h1, h2) 46 while h is not None: 47 print(h.val, end="->") 48 h = h.next
既能朝九晚五,又能浪迹天涯!

浙公网安备 33010602011771号