删除链接列表中的节点时出错 <ListNode.ListNode object at 0x0000000267320>

Error when deleting a node in a Linked List <ListNode.ListNode object at 0x0000000267320>

我正在制作一个 linkedlist,我必须为我的列表添加一些不同的函数,例如 max、min、count 和 index。我现在必须添加一个删除功能,就是这段代码。

def removeItem(self, position):

        ''' removeItem removes a selected, because python has a built in "garbage remover",
        you don't have to physically delete the node, you only have to skip that node link and python will destroy it
        by it self.'''

        currentNode = self.head
        previousNode = None
        count = 0

        while count != position:
            #This is a quick check to make sure the next node isn't empty.
            if currentNode.link is None:
                print("Position Invalid")
                return None
            previousNode = currentNode
            currentNode = currentNode.link
            count += 1

        #Node.Link should link to the next node in the sequence.
        previousNode.link = currentNode.link
        return currentNode

我基本上只是试图 link 遍历序列中的下一个节点,以便内置的垃圾清除器将从序列中删除该节点。但是,我收到以下错误消息,我知道这与我的实例有关。

C:\Python33\python.exe "C:/Users/koopt_000/Desktop/College/Sophomore Semester 2/Computer Science 231/Chapter4/Test.py"
900
1
1
2
<ListNode.ListNode object at 0x0000000002679320>

进程已完成,退出代码为 0

为什么最后打印出这个奇怪的 ListNode.ListNode 对象? 这是我的测试代码:

from ListNode import ListNode
from LinkedList import LinkedList

node1 = ListNode(1)
node2 = ListNode(900)
node3 = ListNode(3)
node4 = ListNode(99)
node1.link = node2
node2.link = node3
node3.link = node4

linked_list = LinkedList((1, 900, 3, 99))
print(linked_list.__max__())
print(linked_list.__min__())
print(linked_list.getCount(900))
print(linked_list.getIndex(3))
print(linked_list.removeItem(3))

这是我的 ListNode 代码 class:

# ListNode.py
class ListNode(object):

    def __init__(self, item = None, link = None):

        '''creates a ListNode with the specified data value and link
        post: creates a ListNode with the specified data value and link'''

        self.item = item
        self.link = link

这是我的 LinkedList 代码 class:

from ListNode import ListNode

class LinkedList(object):

    #--------------------------------------------------------------

    def __init__(self, seq=()):

        """ Pre: Creates a Linked List
        Post: Creates a list containing the items in the seq=()"""

        if seq == ():

            # If there is no items to be put into the list, then it creates an empty one.
            self.head = None

        else:

            # Creates a node for the first item.
            self.head = ListNode(seq[0], None)

            # If there are remaining items, then they're added while keeping track of the last node.
            last = self.head
            for item in seq[1:]:
                last.link = ListNode(item, None)
                last = last.link

        self.size = len(seq)

    #-------------------------------------------------------------

    def __len__(self):

        '''Pre: Nothing.
           Post: Returns the number of items in the list.'''

        return self.size

    #-------------------------------------------------------------
    def __max__(self):

        ''' Goes through each node and compares what the max is for the linked list.
        Post: Finds the max of the linked list and returns that value.'''

        if self.head is None:
        return None
        max_value = self.head.item
        node = self.head.link

        while node is not None:
            if node.item > max_value:
                max_value = node.item
            node = node.link
        return max_value

    #--------------------------------------------------------------

    def __min__(self):

        ''' Goes through each node and compares what the min is for the linked list.
        Post: Finds the min of the linked list and returns that value.'''

        if self.head is None:
            return None
        min_value = self.head.item
        node = self.head.link

        while node is not None:
            if node.item < min_value:
                min_value = node.item
            node = node.link
        return min_value

    #--------------------------------------------------------------

    def getCount(self, yourData):

        ''' This function counts the amount of times a certain item is in the Linked List.'''

        count = 0
        node = self.head

        for i in range(self.size):
            data = node.item
            if data is yourData:
                count += 1
            node = node.link
        return count

    #--------------------------------------------------------------

    def getIndex(self, yourData):

        ''' getIndex finds the index of the selected item and returns that value. '''

        node = self.head

        if node is None:
            return None

        for i in range(self.size):
            data = node.item
            if data == yourData:
                return i
            node = node.link

        raise IndexError


    #--------------------------------------------------------------

    def removeItem(self, position):

        ''' removeItem removes a selected, because python has a built in "garbage remover",
        you don't have to physically delete the node, you only have to skip that node link and python will destroy it
        by it self.'''

        currentNode = self.head
        previousNode = None
        count = 0

        while count != position:
            #This is a quick check to make sure the next node isn't empty.
            if currentNode.link == None:
                print("Position Invalid")
                return None
            previousNode = currentNode
            currentNode = currentNode.link
            count += 1

        #Node.Link should link to the next node in the sequence.
        previousNode.link = currentNode.link
        return currentNode

    #--------------------------------------------------------------

如果有人能帮我找出为什么我的 removeItem 函数不起作用,那将会很有帮助!

附带说明一下,我还试图为该列表创建一个双重 linked 列表,我知道我需要在我的 ListNode 函数中添加一个 prev_node 函数,但是什么我还需要添加吗?再次感谢!

如果您的方法返回 <LinkNode object at 0xmemoryaddr> 字符串,那么它可以正常工作 。您正在打印删除的节点,并且 Python 正在使用该实例的默认 repr() 表示。

如果你想让它更具可读性,你可以给 ListNode 一个 object.__repr__ method:

def __repr__(self):
    next = 'None' if not self.link else '...'  # just to indicate
    return 'ListNode({!r}, {})'.format(self.item, next)

然后将打印 ListNode(99, None) 而不是 <ListNode object at 0xmemoryaddr> 字符串 Python 默认为:

>>> ll = LinkedList((1, 900, 3, 99))
>>> ll.head
ListNode(1, ...)
>>> ll.head.link
ListNode(900, ...)
>>> ll.head.link.link
ListNode(3, ...)
>>> ll.head.link.link.link
ListNode(99, None)

有一件事你必须考虑:你也需要调整列表的长度;成功删除后,从 self.size.

中减去 1