我正在编写 python 中双向链表的代码。但是,我正在努力如何在给定节点之后将数据插入新节点。我的理解在 python 中构建双向链表的insertAfter()方法是错误的。我想知道如何修复代码。
到目前为止,这是我的代码:
class Node:
# Constructor to initialize data
# If data is not given by user,its taken as None
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
class Doubly_Linked_List:
def __init__(self):
self.head = None
self.tail = None
# Inserts data into a new node after the given node
def insertAfter(self, node, data):
runner = Node(None, data, node, None)
runner.next = self.head
if self.head is not None:
self.head.prev = runner
self.head = runner
# # Adds the given value as the last value in the list
def addLast(self, data):
if self.head is not None:
runner = self.head
while(runner.next != None):
runner = runner.next
runner.next = Node(data, None, runner)
self.tail = runner.next
else:
self.head = Node(data)
self.tail = self.head
def Print_Next_List(self): # Traverse forwards
runner = self.head
while (runner is not None):
print(runner.data)
runner = runner.next
def Print_Prev_List(self): # Traverse Backwards
runner = self.tail
while (runner is not None):
print(runner.data)
runner = runner.prev
# Initializing list
aList = Doubly_Linked_List()
aList.addLast(3)
aList.addLast(5)
aList.addLast(7)
aList.addLast(9)
aList.addLast(11)
aList.Print_Next_List()
print()
aList.Print_Prev_List()
aList.insertAfter(5,7) #This shows me an error.
答案 0 :(得分:0)
我不知道你在做什么:
def insertAfter(self, node, data):
runner = Node(None, data, node, None)
runner.next = self.head
if self.head is not None:
self.head.prev = runner
self.head = runner
这应该是:
def insertAfter(self, node, data):
newNode = Node(data, node.next, node)
node.next = newNode
在此创建一个传递数据的新节点,并将其放在传递的节点之后。