[Lintcode]165. Merge Two Sorted Lists/[Leetcode]21. Merge Two Sorted Lists

165. Merge Two Sorted Lists/21. Merge Two Sorted Lists

  • 本题难度: Easy
  • Topic: Linked List

Description

Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.

Example
Example 1:
Input: list1 = null, list2 = 0->3->3->null
Output: 0->3->3->null

Example 2:
Input: list1 = 1->3->8->11->15->null, list2 = 2->null
Output: 1->2->3->8->11->15->null

我的代码

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param l1: ListNode l1 is the head of the linked list
    @param l2: ListNode l2 is the head of the linked list
    @return: ListNode head of linked list
    """
    def mergeTwoLists(self, l1, l2):
        # write your code here
        if l1 is None:
            return l2
        if l2 is None:
            return l1
        res = pos = ListNode(0)
        while(l1 and l2):
            if l1.val <l2.val:
                pos.next = l1
                l1 = l1.next
            else:
                pos.next = l2
                l2 = l2.next
            pos = pos.next
        if l1:
            pos.next = l1
        else:
            pos.next = l2
        return res.next

思路

  1. 之前没有仔细看过python的面向对象编程,因为Linked List中用到了定义新的类,所以简单看了一下教程:Python3 面向对象,写了笔记[Python3] 面向对象编程
  2. 如果一开始就要决定新建第一个点的val,则需要和后面非常重复的判断条件,代码会很繁琐。借鉴了leetcode上的参考答案的思路,头结点仅用于建立链表,最后的结果舍弃掉头结点就好了。
  • 时间复杂度 O(n)
posted @ 2019-02-12 13:47  siriusli  阅读(107)  评论(0编辑  收藏  举报