除反向功能外,其他所有功能均有效。 while循环不会结束。我添加更多细节。我很抱歉。这是我第二次从Stack Overflow获取帮助。
这是完整的代码。我不确定如何发送尾巴以实现反向功能。
非常感谢。我真的很感谢您的所有帮助。
import math
class Node:
def __init__(self, val, next = None, prev = None):
self.data = val
self.next = next
self.prev = prev
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def StartInsert(self, val):
newNode = Node(val)
if self.count == 0:
self.head = newNode
self.tail = newNode
else:
self.head.prev = newNode
newNode.next = self.head
self.head = newNode
self.count += 1
def EndInsert(self, val):
newNode = Node(val)
if self.count == 0:
self.head = newNode
self.tail = newNode
else:
self.tail.next = newNode
newNode.prev = self.tail
self.tail = newNode
self.count += 1
def MiddleInsert(self, val):
newNode = Node(val)
if self.count == 0:
self.head = newNode
self.tail = newNode
else:
index = math.ceil(self.count/2)
temp = self.head
while index > 0:
temp = temp.next
index =- 1
temp.next = Node(val, temp.next)
temp.prev = Node(temp.prev.data, temp)
self.count +=1
def search(self, val):
p = self.head
while p is not None:
if p.data == val:
return p
p = p.next
def delete(self, val):
curNode = self.head
while curNode != None:
if curNode.data == val:
if curNode.prev != None:
curNode.prev.next = curNode.next
else:
self.head = curNode.next
if curNode.next != None:
curNode.next.prev = curNode.prev
else:
self.tail = curNode.prev
self.count -= 1
curNode = curNode.next
def reverse(self):
temp = None
current = self.head
while current != None:
temp = current.prev
current.prev = current.next
current.next = temp
current = current.prev
if temp:
self.head = temp.prev
self.tail=
def traverse(self):
s = ""
p = self.head
while p is not None:
s += str(p.data) + ' ';
p = p.next
print(s + "| count: " + str(self.count))
list = LinkedList()
list.EndInsert("a")
list.StartInsert("b")
list.StartInsert("c")
list.EndInsert("d")
list.MiddleInsert("c")
list.traverse()
print("_________________")
list.reverse()
list.traverse()