美文网首页
21. Merge Two Sorted Lists

21. Merge Two Sorted Lists

作者: Jonddy | 来源:发表于2018-02-20 17:52 被阅读0次
题目要求:

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

巧用头指针

# Time:  O(n)
# Space: O(1)
# 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
        """
        new_head = ListNode(0)     #两个指针指向头节点
        head = new_head            #两个指针指向头节点
        while l1 and l2:
            if l1.val > l2.val:
                new_head.next = l2
                l2 = l2.next
            else:
                new_head.next = l1
                l1 = l1.next        
            new_head = new_head.next  #这一步很重要,自己的习惯是写进上面的if、else里面
            
        if l1:
            new_head.next = l1        
        elif l2:
            new_head.next = l2
            
        return head.next
# Time:  O(n)
# Space: O(1)
# 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
        """
        curr = dummy = ListNode(0)     #两个指针指向头节点,命名更易区分
        while l1 and l2:
            if l1.val < l2.val:
                curr.next = l1
                l1 = l1.next
            else:
                curr.next = l2
                l2 = l2.next
            curr = curr.next           #对于if、else而言都需要的操作可以提取出来
        curr.next = l1 or l2           #python的or操作,那个为真执行哪个
        return dummy.next

相关文章

网友评论

      本文标题:21. Merge Two Sorted Lists

      本文链接:https://www.haomeiwen.com/subject/kagwtftx.html