class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def insertStart(self, data):
nn = Node(data)
self.count +=1
if(self.head==None):
self.head = nn
self.tail = nn
return
nn.next = self.head
self.head.prev = nn
self.head = nn
def insertEnd(self, data):
nn = Node(data)
self.count +=1
if(self.tail is None):
self.head = nn
self.tail = nn
return
nn.prev = self.tail
self.tail.next = nn
self.tail = nn
def insertAtPos(self, data, pos):
nn = Node(data)
if(self.count < pos):
return -1
mid = int(self.count/2)
# print(mid)
if(pos<=mid):
temp = self.head
for i in range(1, pos-1):
temp = temp.next
nn.next = temp.next
nn.prev = temp
temp.next = nn
else:
temp = self.tail
for i in range(self.count-1, pos, -1):
temp = temp.prev
print(temp.data)
nn.prev = temp.prev
nn.next = temp
temp.prev = nn
self.count += 1
def removeStart(self):
self.count -=1
if(self.head is None):
return -1
if(self.count == 1):
self.head = None
self.tail = None
self.head = self.head.next
self.head.prev = None
def removeEnd(self):
self.count -=1
if(self.tail is None):
return -1
self.tail = self.tail.prev
self.tail.next = None
def display(self):
temp = self.head
while(temp is not None):
print(temp.data)
temp = temp.next
dd = DoublyLinkedList()
dd.insertEnd(40)
dd.insertStart(22)
dd.insertEnd(42)
dd.insertStart(20)
dd.insertStart(23)
# dd.display()
print()
dd.removeStart()
dd.removeEnd()
dd.display()
print()
dd.insertAtPos(33, 3)
dd.display()
在insertAtPos
函数中,我的else
部分没有插入新节点,一切似乎都很好,但当我使用显示函数时,添加的新节点不会出现。else
部分存在一些问题。请帮忙!
在其他部分,您忘记添加:
temp.prev.next = nn
并将else
部分中的for loop
更改为:
for i in range(self.count, pos, -1):