我为什么要获得反向双向链表?

问题描述 投票:0回答:2

为什么我要获得反向数据输出=(40-> 30-> 20-> 10->无)。请解决错误:双向链表还有其他方法吗?

class Node:
    def __init__(self,data,next,prev):
        self.data=data
        self.next=next
        self.prev=prev

class linkedlist:
    head=None
    tail=None
    def show(self):
        current_node=self.tail
        while current_node is not None:
            print(current_node.data,"-->",end=" ")
            current_node=current_node.prev
        #self.tail.next=self.head
        print(None)

    def append(self,data):
        node=Node(data,None,None)
        if self.head is None:
            self.head=self.tail=node
        else:
            node.prev=self.tail
            self.tail.next=node
        self.tail=node
s=linkedlist()
s.append(10)
s.append(20)
s.append(30)
s.append(40)
s.show()
print("Doubly Linked List Output")


请解决此错误

python data-structures linked-list doubly-linked-list
2个回答
0
投票

您的show()方法以这种方式工作-它从尾部开始,一直指向列表的头部。从头到尾使用:

    current_node=self.head 
    while current_node is not None:
        print(current_node.data,"-->",end=" ")
        current_node=current_node.next # NEXT!

0
投票

如果要显示为10、20、30、40,请从头开始遍历。您可以将显示方法更改为以

开头
 current_node=self.head 

并且还要确保您在下面更改为

 current_node=current_node.tail.next

每次迭代。

© www.soinside.com 2019 - 2024. All rights reserved.