【LeetCode】面试题25. 合并两个排序的链表

题目:

思路:

1、迭代,每次将两个链表头部较小的节点合并到新链表,最后处理没合并完的链表。
2、递归,当前链表的合并,可以转换为子链表的合并

代码:

Python

# 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
        """
        # if l1 is None:
        #     return l2
        # if l2 is None:
        #     return l1
        # if l2.val < l1.val:
        #     tmp = l2
        #     l2 = l1
        #     l1 = tmp
        # head = l1
        # cur = head
        # l1 = l1.next
        # while l1 is not None and l2 is not None:
        #     if l2.val < l1.val:
        #         tmp = l2
        #         l2 = l1
        #         l1 = tmp
        #     cur.next = l1
        #     cur = l1
        #     l1 = l1.next
        # # l1肯定为None
        # cur.next = l2
        # return head

        # 递归
        if l1 is None:
            return l2
        if l2 is None:
            return l1
        if l1.val < l2.val:
            l1.next = self.mergeTwoLists(l1.next, l2)
            return l1
        else:
            l2.next = self.mergeTwoLists(l1, l2.next)
            return l2

相关问题

posted @ 2020-06-02 11:31  一只背影  阅读(134)  评论(0编辑  收藏  举报