您的位置:首页 > 编程语言 > Python开发

【LeetCode with Python】 Merge Two Sorted Lists

2008-12-07 13:24 573 查看
博客域名:http://www.xnerv.wang

原题页面:https://oj.leetcode.com/problems/merge-two-sorted-lists/

题目类型:

难度评价:★

本文地址:/article/1377545.html

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.

合并两个有序链表,大学期间常见的数据结构练习题。

class Solution:
    # @param two ListNodes
    # @return a ListNode
    def mergeTwoLists(self, l1, l2):
        if None == l1 and None == l2:
            return None
        elif None == l1:
            return l2
        elif None == l2:
            return l1

        new_list = ListNode(0)
        cur = new_list
        node1 = l1
        node2 = l2
        while None != node1 and None != node2:
            if node1.val < node2.val:
                cur.next = node1
                node1 = node1.next
            else:
                cur.next = node2
                node2 = node2.next
            cur = cur.next
        if None != node1:
            cur.next = node1
        else:
            cur.next = node2

        return new_list.next
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: