归并有序链表--Merge Two Sorted Lists
https://oj.leetcode.com/problems/merge-two-sorted-lists/
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.
题目:合并两个已经排序的链表,并实现最终排序。
1 # Definition for singly-linked list.
2 # class ListNode:
3 # def __init__(self, x):
4 # self.val = x
5 # self.next = None
6
7 class Solution:
8 # @param {ListNode} l1
9 # @param {ListNode} l2
10 # @return {ListNode}
11 def mergeTwoLists(self, l1, l2):
12 if l1==None: #一方为空,直接返回另一个链表,无需再用结点排序
13 return l2
14 if l2==None:
15 return l1
16 dummy=ListNode(0) #在确定二链表都不为空后,再建立头结点为下面做准备(前后逻辑顺序)
17 tmp=dummy
18 while l1 and l2:
19 if l1.val<=l2.val: #依次比较和更新l1和l2,遍历整个链表,值小的排在前面
20 tmp.next=l1 #连接一个结点其实代表了整个后面依次连接的结点
21 l1=l1.next
22 tmp=tmp.next
23 else:
24 tmp.next=l2
25 l2=l2.next
26 tmp=tmp.next
27 if l1==None: #当l1所在链表的结点已全部merge完,剩下的l2直接连接上
28 tmp.next=l2
29 else:
30 tmp.next=l1
31 return dummy.next