Python单链表 - 删除元素

时间:2013-12-08 13:19:53

标签: python data-structures

由于某种原因,我的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

1 个答案:

答案 0 :(得分:2)

删除元素时,无需移动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

否则,每次删除元素时,都会通过重新分配previouscursor变量来跳过下一个元素。