LeetCode21--合并两个有序链表

 1 '''
 2 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 3 示例:
 4 输入:1->2->4, 1->3->4
 5 输出:1->1->2->3->4->4
 6 '''
 7 
 8 
 9 class ListNode:
10     def __init__(self, x):
11         self.val = x
12         self.next = None
13 
14 
15 class Solution:
16     def mergeTwoLists(self, l1, l2):
17         """
18         :type l1: ListNode
19         :type l2: ListNode
20         :rtype: ListNode
21         """
22         h = ListNode(-1)
23         cur = h
24         cur1 = l1
25         cur2 = l2
26         while cur1 is not None and cur2 is not None:
27             if cur1.val <= cur2.val:
28                 cur.next = cur1
29                 cur1 = cur1.next
30             else:
31                 cur.next = cur2
32                 cur2 = cur2.next
33             cur = cur.next
34         if cur1 is not None:
35             cur.next = cur1
36 
37         if cur2 is not None:
38             cur.next = cur2
39         return h.next
40 
41 
42 if __name__ == '__main__':
43     list1 = [1, 2, 4]
44     list2 = [1, 3, 4]
45     l1 = ListNode(1)
46     l1.next = ListNode(2)
47     l1.next.next = ListNode(4)
48     l2 = ListNode(1)
49     l2.next = ListNode(3)
50     l2.next.next = ListNode(4)
51     ret = Solution().mergeTwoLists(l1, l2)
52     print(ret)

 

posted @ 2018-12-03 14:52  浅尝辄止易初心不改难  Views(123)  Comments(0Edit  收藏  举报