python实现两个升序链表合并

Posted 江南烟雨尘

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python实现两个升序链表合并相关的知识,希望对你有一定的参考价值。

 1 # Definition for singly-linked list.
 2 class ListNode:
 3     def __init__(self, x):
 4         self.val = x
 5         self.next = None
 6 
 7 
 8 class Solution:
 9     def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
10 
11         new = ListNode(head)
12         new_cur = new
13         while l1 is not None and l2 is not None:
14             if l1.val <= l2.val:
15                 new_cur.next = l1
16                 new_cur = new_cur.next
17                 l1 = l1.next
18             else:
19                 new_cur.next = l2
20                 new_cur = new_cur.next
21                 l2 = l2.next
22 
23         if l1 is None:
24             new_cur.next = l2
25         else:
26             new_cur.next = l1
27 
28         return new.next
29 
30 
31 def Init_node(s: str) -> ListNode:
32     s = s.split(->)
33     head_node = ListNode(head)
34 
35     for i in s:
36         new_node = ListNode(int(i))
37         cur_node = head_node
38         while cur_node.next is not None:
39             cur_node = cur_node.next
40         cur_node.next = new_node
41 
42     return head_node.next
43 def show_node(node:ListNode):
44     while node is not None:
45         print(node.val,end= )
46         node = node.next
47     print(‘‘)
48 
49 if __name__ == __main__:
50 
51     s1 = 1->2->4
52     s2 = 1->3->4
53     list_node_1 = Init_node(s1)
54     list_node_2 = Init_node(s2)
55 
56     solu = Solution()
57     merge = solu.mergeTwoLists(list_node_1, list_node_2)
58     show_node(merge)

 

以上是关于python实现两个升序链表合并的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode练习(Python):链表类:第21题:合并两个有序链表:将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

Leetcode刷题Python21. 合并两个有序链表

leetCode第21题——合并两个有序链表

奇数结点升序偶数结点降序的单链表排序(Python实现)

力扣LeetCode合并两个有序链表

#yyds干货盘点# LeetCode面试题:合并两个有序链表