合併兩個已排序的鏈表

合併兩個已排序的鏈表

Merge Two Sorted Lists

  • 合併兩個已排序的鏈表,新鏈表中的每一個節點必須是來自輸入的兩個鏈表的節點(即不能構造新的節點),返回新鏈表的頭部。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

思路

  1. head指向輸入兩個鏈表中頭節點較小值,做爲新鏈表的頭部code

  2. tail指向新鏈表表尾,初始狀態head = tail排序

  3. a掃描l1,b掃描l2,比較ab節點內值的大小,將較小的加入tail以後,ab中較小的向後移動一個節點,較大的不動,tail向後移動一個節點保證任意時候指向都是新鏈表尾部ci

  4. l1l2其中一個已經遍歷完,若另外一個還有元素,添加到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

相關文章
相關標籤/搜索