从链表(堆栈)中删除节点

Removing a node from a linked list (stack)

我必须在堆栈中编写一个链表,这意味着我只能删除最顶部的数字并从堆栈顶部压入一个数字。不幸的是我的 pop() 函数没有工作,我希望你能帮助我:

# ---------------init--------------
class node:
    def __init__(self):
        self.data = None # contains the data
        self.next = None # contains the reference to the next node


class linked_list:
    def __init__(self):
        self.cur_node = None

# ---------------is_empty--------------
    def is_empty(self):
    if self.cur_node == None:
        print ("list is empty")
    else:
        print ("List = ")
        ll.list_print()

# ---------------is_full--------------

# ---------------push--------------

    def push(self, data):
        new_node = node() # create a new node
        new_node.data = data
        new_node.next = self.cur_node # link the new node to the 'previous' node.
        self.cur_node = new_node #  set the current node to the new one.

# ---------------pop--------------

    def pop(self):
    print(node)
    node = self.cur_node
    while node:
        if node.next == None:
        node = None
        break 
        else:
        node=node.next


# ---------------print--------------
    def list_print(self):
        ...


ll = linked_list()

ll.is_empty()
ll.push(1)
ll.push(3)
ll.push(2)
ll.is_empty()
ll.pop()
ll.list_print()

当前pop()前的输出为

2
3
1

pop()之后应该是

3
1

弹出功能可能对你有帮助

 def pop(self, i):
        '''(LinkedList, int) -> NoneType
        Remove and return item at index. Raise IndexError if list is empty or
        index is out of range.'''

        if i < 0 or i >= self.num_elements:
            raise IndexError("pop index out of range")
        if i == 0:
            result = self.front.key
            self.front = self.front.next
        else:
            node = self.front
            for j in range(i - 1):
                node = node.next
            result = node.next.key
            node.next = node.next.next
        self.num_elements -= 1
        return result

您的代码当前遍历堆栈并且未修改任何内容。

想想调用函数时栈的状态。在您的示例中,它是这样的:

调用pop()后,你希望它是这样的:

因此,您只需将 self.cur_node 设置为 self.cur_node.next。您无需执行任何操作即可删除包含 2 的节点,Python 将在不再被引用后自动执行此操作。