[英]Python singly linked list - removing an element
由於某種原因,我的remove_element方法不會刪除包含元素的所有節點。 為什么?
class Node:
def __init__(self, element):
self.element = element
self.next = None
class SLL:
def __init__(self):
self.head = None
# add a node to front
def add_front(self, element):
new_node = Node(element)
if self.head == None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
# removes from the head
def remove(self):
if self.head == None:
print "Error: the list is empty."
else:
self.head = self.head.next
# removes all nodes which hold a given element
def remove_element(self, element):
previous = None
cursor = self.head
while cursor != None:
if cursor.element == element:
if cursor == self.head:
self.remove()
else:
previous.next = cursor.next
previous = cursor
cursor = cursor.next
# traverses the list and prints out its elements
def print_list(self):
cursor = self.head
while (cursor != None):
print(cursor.element)
cursor = cursor.next
# Main
SLL = SLL()
SLL.add_front(21)
SLL.add_front(21)
SLL.add_front(1)
SLL.add_front(1)
SLL.add_front(1)
SLL.add_front(2)
SLL.add_front(3)
SLL.add_front(5)
SLL.add_front(8)
SLL.add_front(13)
SLL.add_front(21)
SLL.print_list()
print
SLL.remove_element(1)
SLL.print_list()
print
輸出:
bash-3.2$ python SLL.py
21
13
8
5
3
2
1
1
1
21
21
21
13
8
5
3
2
1 <--- What is this guy doing here?
21
21
刪除元素時,無需移動上previous
變量引用:
while cursor != None:
if cursor.element == element:
if cursor == self.head:
self.remove()
else:
previous.next = cursor.next
else:
previous = cursor
cursor = cursor.next
否則,每次刪除元素時,都會通過重新分配previous
和cursor
變量來跳過下一個元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.