leetcode with python:21. Merge Two Sorted Lists

题目:

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

给定两个排序过的linked list,将两个整合成一个新的 sorted linked list

整体来说,这题便是linked list操作的练习

# Definition for singly-linked list.# class ListNode:#     def __init__(self, val=0, next=None):#         self.val = val#         self.next = nextclass Solution:    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:        if not list1:      #一旦其中一个是None,两者就不用整合了            return list2        if not list2:            return list1                    ll=ListNode() #纪录欲回传linkedlist的head        ans=ll                while True:            if list1.val>=list2.val:                ll.next=list2                list2=list2.next            else:                ll.next=list1                list1=list1.next            ll=ll.next                        if list1==None:                ll.next=list2                break            if list2==None:                ll.next=list1                break        return ans.next

将两linked list的值逐一比较,较小的值填入新的linked list(ll)内,给值的linked list进入下一项
直到其中一个linked list跑完,另外一个还有剩的话就将剩下全部接到ll之后(因为剩下的值都>ll的最后一项)
最终ll便成为新的sorted merged linked list
最后执行时间为34ms(faster than 97.14%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章