删除链接列表中的头节点

时间:2016-10-24 02:34:44

标签: python data-structures linked-list

如何修复delete方法以便它还可以删除头节点?

class LinkedListNode():
    def __init__(self, data=None, next_node=None):
        self.data = data
        self.next_node = next_node


    def data(self):
        return self.data


    def next_node(self):
        return self.next_node


    def set_next_node(self, next_node):
        self.next_node = next_node

    def search(self, data):
        index = 0
        while self.next_node != None and self != None:
            if self.data == data:
                return index
            else:
                self = self.next_node
                index += 1
        return -1

    def delete(self, data):
        head = self
        if self.data == data:
            head = self.next_node
        while self.next_node != None and self != None:
            if self.next_node.data == data:
                if self.next_node.next_node != None:
                    self.next_node = self.next_node.next_node
                else:
                    self.next_node = None
            else:
                self = self.next_node
        return head


    def print(self):
        while self.next_node != None:
            print("%s: %s" % ("current node data is", self.data))
            self = self.next_node
        if self.next_node == None and self != None:
            print("%s: %s" % ("current node data is", self.data))

在测试文件中我有:

from LinkedListNode import *

head = LinkedListNode(3)
node1 = LinkedListNode('cat')
node2 = LinkedListNode('dog')
node3 = LinkedListNode(4)
head.set_next_node(node1)
node1.set_next_node(node2)
node2.set_next_node(node3)

print(head.search('dog'))
head.delete(3)
head.delete(4)
head.print()

我明白了:

2
current node data is: 3
current node data is: cat
current node data is: dog

Process finished with exit code 0

1 个答案:

答案 0 :(得分:0)

首先,我相信你不应该在搜索方法中重新分配'self':

eval(f)

将其替换为简单的递归版本,然后重试:

def search(self, data):
    index = 0
    while self.next_node != None and self != None:
        if self.data == data:
            return index
        else:
            self = self.next_node
            index += 1
    return -1