脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python实现合并两个有序链表的方法示例

Python实现合并两个有序链表的方法示例

2021-05-25 00:18lin-chang Python

这篇文章主要介绍了Python实现合并两个有序链表的方法,涉及Python操作链表节点的遍历、判断、添加等相关操作技巧,需要的朋友可以参考下

本文实例讲述了python实现合并两个有序链表的方法。分享给大家供大家参考,具体如下:

Python实现合并两个有序链表的方法示例

思路:先选出第一个节点,然后遍历两个链表,把小的作为当前节点的下一个节点,一直到其中一个链表遍历完,这时候把另一个链表直接接上就好

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 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
    """
    #先考虑链表其中一个为空的情况
    if not l1:
      return l2
    if not l2:
      return l1
    curnode1 = l1
    curnode2 = l2
    #先选出第一个节点
    if curnode1.val < curnode2.val:
      head = curnode1
      curnode1 = curnode1.next
    else:
      head = curnode2
      curnode2 = curnode2.next
    cur = head
    while curnode1 and curnode2:
      if curnode1.val < curnode2.val:
        cur.next = curnode1
        curnode1 = curnode1.next
      else:
        cur.next = curnode2
        curnode2 = curnode2.next
      cur = cur.next
    #一直循环到有一个链表先结束
    #如果是链表1先结束,则拼上链表2剩余的那段
    if not curnode1:
      cur.next = curnode2
    #如果是链表2先结束,则拼上链表1剩余的那段
    else:
      cur.next = curnode1
    return head

Python实现合并两个有序链表的方法示例

希望本文所述对大家python程序设计有所帮助。

原文链接:https://blog.csdn.net/u011583025/article/details/85399644

延伸 · 阅读

精彩推荐