LeetCode primary algorithm - list 02: Merge two ordered lists

LeetCode primary algorithm - list 02: Merge two ordered lists

Search micro-channel public number: 'AI-ming3526' or 'this small computer vision' for more algorithms, machine learning, dry
CSDN: https://blog.csdn.net/baidu_31657889/
CSDN: HTTPS: //blog.csdn. NET / abcgkj /
GitHub: https://github.com/aimi-cn/AILearners

First, the primer

It was launched by the LeetCode official list of interview questions classics -
this module is to explore the corresponding primary algorithm - designed to help entry-algorithm. Our first pass leetcode brush is recommended topics.
View the complete algorithm Offer to prove safety issues resolved, please click on the link github:
github address

Second, the title

The two ordered lists merged into a new order list and return. The new list is by all nodes in a given mosaic composed of two lists.

Example:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

1, ideas

A number of first ordered list we see we can first compare the two lists of equal length portions, arranged in order, for the remaining part of a linked list, directly into the final list, the detailed procedure, see code.

2, programming

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
        """
        new_head = ListNode(0)
        #返回的是合并后的列表 所以让一个节点等于这个空的节点
        pHead = 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 l1:
            new_head.next = l1
        elif l2:
            new_head.next = l2
        return pHead.next

AIMI-CN AI learning exchange group [1015286623] for more information on AI

Sharing technology, fun in life: our number of public computer vision this small push "AI" series News articles per week, welcome your interest!

This article from the blog article multiple platforms OpenWrite release!

Guess you like

Origin www.cnblogs.com/aimi-cn/p/11716801.html