leetcode21 Merge Two Sorted Lists

 1 """
 2 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.
 3 Example:
 4 Input: 1->2->4, 1->3->4
 5 Output: 1->1->2->3->4->4
 6 """
 7 class ListNode:
 8     def __init__(self, x):
 9         self.val = x
10         self.next = None
11 
12 class Solution:
13     def mergeTwoLists(self, l1, l2):
14         head = ListNode(0)
15         first = head         #!!!结果头指针
16         while l1 != None and l2 != None:
17             if l1.val <= l2.val:
18                 head.next = l1
19                 l1 = l1.next
20             else:
21                 head.next = l2
22                 l2 = l2.next
23             head = head.next #!!!跟随新链表增长的指针
24         if l1 == None:       #bug这个判别条件应该写在while之后
25             head.next = l2
26         elif l2 == None:
27             head.next = l1
28         return first.next
原文地址:https://www.cnblogs.com/yawenw/p/12273855.html