[英]Implementation of doubly linked list
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()
In the insertAtPos
function, my else
part is not inserting the new node, everything seems to work fine but when I use display function new node that is added is not appearing.在insertAtPos
function 中,我的else
部分没有插入新节点,一切似乎都工作正常,但是当我使用显示 function 添加的新节点时没有出现。 There's some problem in the else
part. else
部分有问题。 Please help!请帮忙!
In else part, you forgot to add:在其他部分,您忘记添加:
temp.prev.next = nn
And change for loop
in else
part to:并将else
部分中for loop
更改为:
for i in range(self.count, pos, -1):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.