Leetcode-Merge Two Sorted Lists-Python

Merge Two Sorted Lists

合并两个有序链表。
Description

解题思路
此题比较简单,采用迭代的方式。由于链表已经是有序的,所以依次比较两个链表当前元素的大小,然后将较小的元素加入到新的链表中。

# 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
        """
        result = cur = ListNode(1)       # 第一个节点可以任取
        while l1 and l2:
            if l1.val < l2.val:
                cur.next = l1
                l1 = l1.next
            else:
                cur.next = l2
                l2 = l2.next
            cur = cur.next
        cur.next = l1 or l2
        return result.next

猜你喜欢

转载自blog.csdn.net/ddydavie/article/details/77455381
今日推荐