简体   繁体   English

推入并弹出堆栈

[英]Push and pop in stack

This is the push and pop functions written by Codility (source: https://codility.com/media/train/5-Stacks.pdf ) 这是Codility编写的push和pop函数(来源: https ://codility.com/media/train/5-Stacks.pdf)

stack = [0] * N
size = 0
def push(x):
    global size
    stack[size] = x
    size = size + 1
def pop():
    global size
    size = size - 1
    return stack[size]

I see that the only thing that the function pop() does is to decrement the value of size by 1, and return stack[size]. 我看到函数pop()唯一要做的就是将size的值减1,然后返回stack [size]。 How does it actually remove the last element from the stack? 它实际上如何从堆栈中删除最后一个元素? I don't really see it... 我真的没看到...

You need to distinguish between the stack as a concept and the list which implements it. 您需要区分作为概念的堆栈和实现堆栈的列表。 In this implementation, the stack only consists of elements of the list whose index is less than the stack size. 在此实现中,堆栈仅由列表中索引小于堆栈大小的元素组成。

When the stack size is 0, there is nothing on the stack, because there are no list indices less than 0. 当堆栈大小为0时,堆栈上没有任何内容,因为没有列表索引小于0。

After the first push, the stack size is 1, so there is exactly one list element that corresponds to a stack element: stack[0] . 第一次推送后,堆栈大小为1,因此恰好有一个与堆栈元素相对应的列表元素: stack[0]

If you then pop an element, the stack size is again reduced from 1 to 0, so the stack is again empty. 如果随后pop一个元素,则堆栈大小会再次从1减小为0,因此堆栈会再次为空。

At no point does the size of the list change, only the number of list elements that are considered to represent stack elements. 列表的大小在任何时候都不会改变,只会改变被认为代表堆栈元素的列表元素的数量。

You may be expecting an implementation in which there is always a one-to-one correspondence between stack elements and list elements: 您可能期望实现其中堆栈元素和列表元素之间始终一一对应的实现:

stack = []

pop = stack.pop
push = stack.append

看来,下次调用push()时,它只是覆盖了元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM