python中有序链表_Python实现“合并两个有序链表”的两种方法

本文介绍如何在Python中合并两个有序链表,分别通过将l2节点逐一插入l1和创建新的l3链表进行拼接。详细阐述了两种方法的实现过程和代码示例。
摘要由CSDN通过智能技术生成

合并两个有序链表,并返回一个新的链表。新链表由前两个链表拼接而成。

Example:

Input: 1->2->4, 1->3->4

Output: 1->1->2->3->4->4

1:将l2链表中的结点一个一个的单独插入l1链表中

# 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 and not l2: #l1和l2链表均不存在

return None

if not l1: #l1链表不存在

return l2

if not l2: #l2链表不存在

return l1

while l2: #将l2链表中的结点一个一个插入l1链表中

l2_temp_node = ListNode(l2.val) #将l2中结点赋值为新结点,链表作为参数进行函数传递会随函数进行动态变换

l1 = nodeInsert(l1,l2_temp_node)

l2 = l2.next

return l1

def nodeInsert(l1, node):

head_node = ListNode(0) #头指针

head_node.next = l1

moder_node = ListNode(0) #指向当前结点的前一个结点

if node.val < l1.val: #结点小于头结点

node.next = l1

head_node.next = node

return head_node.next

moder_node = l1 #链表往后移一位

l1 = l1.next

while l1: #遍历判断链表

if l1.val>node.val: #判断

node.next = l1

moder_node.next = node

return head_node.next

else: #往后遍历链表

moder_node=l1

l1=l1.next

moder_node.next = node #结点大于链表中任意结点

return head_node.next

2:声明第三个链表作为转接

# 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 and not l2: # l1和l2链表均不存在

return None

if not l1: # l1链表不存在

return l2

if not l2: # l2链表不存在

return l1

l3 = ListNode(0)

l3_head_node = l3

while l1 is not None and l2:

if l1.val <= l2.val:

l3.next = l1

l1 = l1.next

else:

l3.next = l2

l2 = l2.next

l3 = l3.next

if l1 is not None:

l3.next = l1

else:

l3.next = l2

return l3_head_node.next

算法题来自:https://leetcode-cn.com/problems/merge-two-sorted-lists/description/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值