Q21 Merge Two Sorted Lists

2018-02-28  本文已影响10人  牛奶芝麻

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.

Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
解题思路:

创建一个新链表,包括头结点和工作结点。在比较的过程中为工作结点的后续创建新的结点,直至有一个链表为空。最后,把另一个链表全部加入到工作结点的后续。

注意点:

Pyhon链表中,一个链表不可以赋值给一个结点,如 cur = l2、cur = l2.next (l2为链表),但是可以把链表赋值给一个结点的地址,如 cur.next = l2、cur.next = l2.next (l2为链表)

Python实现:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = ListNode(-1)  # 返回头结点
        cur = head # 当前结点
        while l1 != None and l2 != None:
            if l1.val <= l2.val:
                cur.next = ListNode(l1.val) # 为cur的后续创建一个结点
                l1 = l1.next
            else:
                cur.next = ListNode(l2.val)
                l2 = l2.next
            cur = cur.next  # 当前结点后移
        if l1 == None:  # 如果一个链全部遍历完,则将另外一个链接到后面
            cur.next = l2
        if l2 == None:
            cur.next = l1
        return head.next   # 返回合并好的新链表        
上一篇下一篇

猜你喜欢

热点阅读