python单链表排序_排序双链表Python

本文介绍了一个Python初学者在构建和操作双重链表(SortedDoublyLL)时遇到的问题,通过实例代码演示了如何创建节点、排序和初始化链表。重点在于理解链表的双向链接结构和相关操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我在理解和实现双重链接列表时遇到了困难。我能掌握链表的大部分概念。以下是我目前为止的代码(用Python编写)

*这是纯粹的学术练习。我通常使用list和dictclass DoublyNode(object):

"""A node of the SortedDoublyLL object.

DoublyNode(item, next=None, previous=None) -> a new DoublyNode with data as

its data, and next and previous as its neighbors."""

def __init__(self, data, next = None, previous = None):

"""Make a new DoublyNode from item, pointing to next and previous."""

self.data = data

self.next = next

self.previous = previous

class SortedDoublyLL(object):

"""A Sorted Doubly Linked List.

SortedDoublyLL() -> new SortedDoublyLL list that is empty

SortedDoublyLL(sequence) -> a SortedDoublyLL initialized from sequence's

items.

"""

def __init__(self, sequence = []):

"""Make a new SortedDoublyLL from the elements of sequence."""

if len(sequence) == 0:

self.head = None

self.tail = None

else:

cur_node = None

prev_node = None

sequence.sort()

sequence.reverse()

for element in sequence:

prev_node = cur_node

cur_node = DoublyNode(element, cur_node, prev_node)

self.head = cur_node

self.tail = DoublyNode(sequence[0])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值