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

时间:2015-01-09 20:06:40

标签: python 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

2 个答案:

答案 0 :(得分:1)

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

在调用函数时考虑堆栈的状态。在你的例子中,它是这样的:

stack before pop

致电pop()后,您希望它如下:

stack after pop

所以您需要做的就是将self.cur_node设置为self.cur_node.next。您不必做任何事情来删除包含2的节点,Python将在不再被引用时自动执行此操作。

答案 1 :(得分:0)

pop功能可能会帮助你

 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