本文主要是介绍Merge Two Sorted Lists - LeetCode,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Merge Two Sorted Lists - LeetCode
题目:
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.
分析:
我选择的方式是直接进行比较,并且新建一个空间储存排序结果。注意的一点就是链表l1和l2会移动到为None的地步。
代码:
class Solution:# @param two ListNodes# @return a ListNodedef mergeTwoLists(self, l1, l2):if not l1 and not l2:return Nonel4 =l = ListNode(0)while l1 and l2:if l1.val >= l2.val:l.next= ListNode(l2.val)l2 = l2.nextelif l1.val < l2.val:l.next = ListNode(l1.val)l1 = l1.nextl = l.next if not l1 and l2:l.next = l2if not l2 and l1:l.next = l1return l4.next
这篇关于Merge Two Sorted Lists - LeetCode的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!