Python:删除节点链接列表

时间:2018-07-30 17:27:38

标签: python linked-list

我对Python相当陌生,正尝试从链接列表(而不是尾部)中删除一个节点,并收到错误消息:AttributeError:'int'对象没有属性'next'。显然,delete_middle_node出了点问题,但是我不明白是什么!

编辑:完整的错误消息是:

Traceback (most recent call last):
  File "delete_middle_node.py", line 48, in <module>
    delete_middle_node(middle_node)
  File "delete_middle_node.py", line 35, in delete_middle_node
    if not node.next:
AttributeError: 'int' object has no attribute 'next'

这就是我所拥有的:

class Node(object):
    """Class in a linked list."""

    def __init__(self, data, next=None):
        self.data = data
        self.next = next

class LinkedList(object):
    '''Linked List using head and tail'''

    def __init__(self):
        self.head = None
        self.tail = None

    def list_print(self):
        node = self.head
        while node:
            print node.data
            node = node.next

    def add_node(self, data):
        '''Add node with data to end of list.'''

        new_node = Node(data)

        if self.head is None:
            self.head = new_node

        if self.tail is not None:
            self.tail.next = new_node

        self.tail = new_node

def delete_middle_node(node):
    if not node.next:
        raise ValueError('Cannot remove tail node')
    node.data = node.next.data
    node.next = node.next.next

ll = LinkedList()
ll.add_node(300)
ll.add_node(20)
middle_node = 50
ll.add_node(middle_node)
ll.add_node(10)
ll.add_node(15)
delete_middle_node(middle_node)
ll.list_print()

1 个答案:

答案 0 :(得分:0)

middle_node是一个整数。您正在将其传递给需要delete_middle_node对象的Node

您可以这样解决它:

class LinkedList(object):
    '''Linked List using head and tail'''

    ...

    def add_node(self, data):
        '''Add node with data to end of list.'''

        new_node = Node(data)

        if self.head is None:
            self.head = new_node

        if self.tail is not None:
            self.tail.next = new_node

        self.tail = new_node

        # returning the newly created Node object
        return new_node

...

middle_node = 50
mid_node = ll.add_node(middle_node)
...
delete_middle_node(mid_node)
...