leecode-21. 合并两个有序链表 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 1234示例:输入:1->2->4, 1->3->4输出:1->1->2->3->4->4 解法一:123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051#!/usr/bin/env python# -*- coding: utf-8 -*-# author:sarizzm time:2020/12/24 0024# Definition for singly-linked list.class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = nextclass Solution: def mergeTwoLists(self, l1, l2): if not l1:return l2 if not l2:return l1 p1 = l3 = ListNode() while (l1 and l2): if l1.val < l2.val: p1.next = l1 l1 = l1.next p1 = p1.next else: p1.next = l2 l2 = l2.next p1 = p1.next if l1 == None: p1.next = l2 return l3.next else: p1.next = l1 return l3.nextdef generateNode(nx): node = ListNode() p1 = node for i in nx: p1.next = ListNode(i) p1 = p1.next return node.nextn1 = [1,3,5,7,10]n2 = [2,4,6,8,9]node1 = generateNode(n1)node2 = generateNode(n2)# while(node1):# print(node1.val)# node1 = node1.nextnode3 = Solution().mergeTwoLists(node1,node2)while(node3): print(node3.val) node3 = node3.next 解法二1234567891011121314151617class Solution: def mergeTwoLists(self, l1, l2): if l1 is None: return l2 elif l2 is None: return l1 elif l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2#作者:LeetCode-Solution#链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/ 1234567891011121314151617181920class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) { return l2; } else if (l2 == null) { return l1; } else if (l1.val < l2.val) { l1.next = mergeTwoLists(l1.next, l2); return l1; } else { l2.next = mergeTwoLists(l1, l2.next); return l2; } }}//作者:LeetCode-Solution//链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/ 文章作者: zhouzhm文章链接: https://sarizzm.github.io/2020/12/23/leecode-21-he-bing-liang-ge-you-xu-lian-biao/版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 codemk!leecode 打赏wechatalipay上一篇leecode-20-有效的括号下一篇leecode-21-合并两个有序链表 相关推荐 2020-05-03leecode-01-twosum(两数之和) 2020-05-05leecode-02-two-sum 2020-05-06leecode-03-lengthOfLongestSubstring 2020-05-22leecode-04-median-of-two-sorted-arrays 2020-12-21leecode-13 罗马数字转整数 2020-12-21leecode-14 最长公共前缀 评论