#leetcode 021 Merge Two Sorted Lists(Python)

来源:互联网 发布:手游英雄杀十连抽数据 编辑:程序博客网 时间:2024/05/17 22:08

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.

将两个排好序的链表拼接成一个新的链表

# Definition for singly-linked list.# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    # @param {ListNode} l1    # @param {ListNode} l2    # @return {ListNode}    def mergeTwoLists(self, l1, l2):        if l1 == None:            return l2        if l2 == None:            return l1        if l1.val>l2.val:            temp = l2            l2 = l1            l1 = temp        l = l1        while l2 != None:            if l1.next==None:                l1.next = l2                break            if l1.next.val > l2.val:                temp = l1.next                l1.next = l2                l2 = l2.next                l1 = l1.next                l1.next = temp            else:                l1 = l1.next        return l
0 0
原创粉丝点击