python - 单向链表的反向链接方向

标签 python algorithm linked-list

我有一个反向链接的链表,在这个程序中有什么方法可以改变链接的方向吗?我试过使用 self.head.set_next 从第一个元素开始,但是类型 None 没有方法 set_next,所以我我不确定我将如何进行。

class Node2(object):
    def __init__(self, data=None, next_node=None):
        self.data = data
        self.next_node = next_node

    def set_next(self, new_next):
        self.next_node = new_next

    def get_data(self):
        return self.data

    def get_next(self):
        return self.next_node

class LinkedList2(object):
    def __init__(self, head=None):
        self.head = head

    def insert(self, data):
        new_node = Node(data)
        new_node.set_next(self.head)
        self.head = new_node

最佳答案

这样的东西就可以了

# linked_list is the list you want to reverse
previous_node = None
current_node = linked_list.head

while current_node is not None:
    next_node = current_node.get_next()
    current_node.set_next(previous_node)
    previous_node, current_node = current_node, next_node

linked_list.head = previous_node

这将在线性时间内执行。

但是,如果你发现你需要频繁地反向链表,你可能会发现doubly linked lists更贴合您的需求

关于python - 单向链表的反向链接方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35467798/

相关文章:

java - 如何在 Java 中实现随机 O(n) 算法来查找未排序数组的中位数?

c - 在链表中查找两个最小元素

python - 在新的本地化项目中处理遗留的 django 项目

python - 实现特定的比较功能

python - 将函数应用于列表的任意两个元素 - Python

c# - 在 C# 平面中绘制粗细可变的羽化线

创建具有三个节点的链表

c - 从单链表打印结构数据

python - scikit随机森林sample_weights的使用

python - 训练模型来预测简单的线性函数