我试图实现一个有序的链表。这是代码:
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
以及测试用例:
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
我很难过为什么它不会工作。
答案 0 :(得分:0)
删除第一个元素时,您正在清除整个链接列表:
elif found and previous is None:
self.head = None
此处previous
为None
,因为您从未将previous
设置为其他任何内容。第一个元素current
匹配。
您需要以不同方式处理此案例:
elif found and previous is None:
self.head = current and current.get_next()