[英]Ordered Linked List in Python: AssertionError
I have trying to implement an ordered linked list. 我试图实现一个有序的链表。 Here's the code: 这是代码:
class Node:
def __init__(self, initial_data):
self.data = initial_data
self.next = None
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_data(self, new_data):
self.data = new_data
def set_next(self, new_next):
self.next = new_next
class LinkedList:
def __init__(self):
self.head = None
def __str__(self):
output_string = ''
current = self.head
while current is not None:
output_string += str(current.get_data())
next_node = current.get_next()
#gives the pointer to the next node i.e. the next node is that which is next to the current
if next_node is not None:
output_string += "->"
current = next_node
return output_string
#does not need to be changed for ordered linked list
def is_empty(self):
if self.head is None:
return True
else:
return False
def insert(self, data):
current = self.head
previous = None
stop = False
while current is not None and not stop:
if current.get_data() > data:
stop = True
else:
previous = current
current = current.get_next()
temp = Node(data)
if previous == None:
temp.set_next(self.head)
self.head = temp
else:
temp.set_next(current)
previous.set_next(temp)
def size(self):
current = self.head
count = 0
while current != None:
count += 1
current = current.get_next()
return count
def search(self, item):
current = self.head
found = False
stop = False
while current is not None and not found and not stop:
if current.get_data()== item:
found = True
else:
if current.get_data() > item:
stop = True
else:
current = current.get_next()
return found
def delete(self, item):
current = self.head
previous = None
found = False
while current is not None and not found:
if current.get_data() == item:
found = True
break
else:
previous = current
current = current.get_next()
if found and previous is not None:
previous.set_next(current.get_next())
elif found and previous is None:
self.head = None
and here's the test case: 这是测试用例:
def test_delete_smallest():
my_list = LinkedList()
my_list.insert(31)
my_list.insert(77)
my_list.insert(17)
my_list.insert(93)
my_list.insert(26)
my_list.insert(54)
assert my_list.size() == 6
my_list.delete(17)
assert my_list.size() == 5
I'm rather stumped as to why it won't work. 我很困惑为什么它不起作用。
You are clearing your whole linked list when you are deleting the first element: 删除第一个元素时,您正在清除整个链表:
elif found and previous is None:
self.head = None
Here previous
is None
because you never set previous
to anything else. previous
是“ None
因为您永远不会将其他设置为previous
。 The first element current
matches. 第一元件current
相匹配。
You'll need to handle this case differently: 你需要以不同的方式处理这种情况:
elif found and previous is None:
self.head = current and current.get_next()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.