合併兩個已排序的鏈表,新鏈表中的每一個節點必須是來自輸入的兩個鏈表的節點(即不能構造新的節點),返回新鏈表的頭部。node
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.git
example 1github
input: 1->2->4, 3->8 output: 1->2->3->4->8
head
指向輸入兩個鏈表中頭節點較小值,做爲新鏈表的頭部code
tail
指向新鏈表表尾,初始狀態head = tail
排序
a
掃描l1
,b掃描l2
,比較a
和b
節點內值的大小,將較小的加入tail
以後,a
和b
中較小的向後移動一個節點,較大的不動,tail向後移動一個節點保證任意時候指向都是新鏈表尾部ci
l1
和l2
其中一個已經遍歷完,若另外一個還有元素,添加到tail
以後leetcode
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if None in (l1, l2): return l1 or l2 head = tail = l1 if l1.val <= l2.val else l2 a = l1 if l1.val > l2.val else l1.next b = l2 if l1.val <= l2.val else l2.next while a and b: if a.val <= b.val: tail.next = a tail, a = tail.next, a.next else: tail.next = b tail, b = tail.next, b.next tail.next = a or b return head
本題以及其它leetcode題目代碼github地址: github地址get