0

我已经让代码工作了,但是我已经在 python 中编写了实现堆栈的代码,它在 LIFO 之后推送和弹出,但是当您查看列表时,它会将其打印为:

1 
2 
3 

显示底部的最后一项是 3,我怎样才能让它像正确的堆栈一样在顶部显示最后一项?

我的代码如下:

stack_pointer = 0
stack =[]
max_length = 2


def view():
        for x in range (len(stack)):
            print(stack[x])
def push():
    global stack_pointer
    if len (stack)> max_length:
        print("Maximum stack length reached!") 
    else:
        stack_pointer = stack_pointer + 1
        item = input("Please enter the  item you wishto add to the stack: ")
        stack.append(item)

def pop():
    global stack_pointer
    if len (stack)<= 0:
        print ("stack is empty!")
    else:
        item = stack.pop
        stack_pointer = stack_pointer - 1
        print ("you just popped out: ", item)

while True:
    print ("")
    print("Python implementation of a stack")
    print("********************************")
    print("1. view Stack")
    print("2. Push onto Stack")
    print("3. Pop out of Stack")
    print("********************************")
    print("")
    menu_choice = int (input("Please enter your menu choice: "))
    print ("")
    print ("")

    if menu_choice == 1:
        view()
    elif menu_choice == 2:
        push()
    elif menu_choice == 3:
        pop()
4

2 回答 2

1

尝试这样的事情:

def view():
    print(list(reversed(stack)))

创建列表的反向副本并将其打印出来。

于 2016-01-15T00:28:27.230 回答
0

这应该有效:start堆栈长度的 a - 1 ,stop-1 的 a 和 -1step的 a;没有创建新列表或任何额外的操作,只修改range对象参数,因此它很有效:

def view():
    for x in range (len(stack) - 1, -1, -1):
        print(stack[x])  # or print(stack[x], end=' ')
于 2016-01-15T00:23:06.943 回答