列表

详情


NP29. 用列表实现栈

描述

栈是一种先进后出的数据结构,类似我们生活中挤电梯,最后进入的肯定是先出来,现我们用Python的列表来模拟栈。假设初始的列表为 stack = [1, 2, 3, 4, 5],请将其视作栈,使用pop函数弹出末尾两个元素,再使用append函数将输入元素加入到栈中,每次操作完成后都要输出整个列表。

输入描述

输入要加入栈中的整数。

输出描述

第一行输出第一次出栈后的列表;
第二行输出第二次出栈后的列表;
第三行输出元素入栈后的列表。

示例1

输入:

1

输出:

[1, 2, 3, 4]
[1, 2, 3]
[1, 2, 3, 1]

说明:

第一次弹出末尾元素5,第二次弹出末尾元素4,第三次加入新增元素1

原站题解

Python 解法, 执行用时: 10ms, 内存消耗: 2824KB, 提交时间: 2022-08-05

stack = [1, 2, 3, 4, 5]
a=stack.pop()
print(stack)
b=stack.pop()
print(stack)
a=int(input())
stack.append(a)
print(stack)

Python 解法, 执行用时: 10ms, 内存消耗: 2840KB, 提交时间: 2022-08-03

num = int(input())
stack = [1, 2, 3, 4, 5]
stack.pop()
print(stack)
stack.pop()
print(stack)
stack.append(num)
print(stack)

Python 解法, 执行用时: 10ms, 内存消耗: 2840KB, 提交时间: 2022-07-31

stack = [1, 2, 3, 4, 5]
a=int(input())
for b in range(2):
    stack.pop()
    print(stack)
stack.append(a)
print(stack)

Python 解法, 执行用时: 10ms, 内存消耗: 2860KB, 提交时间: 2022-08-05

stack = [1, 2, 3, 4, 5]
stack.pop()
print(stack)
stack.pop()
print(stack)
a=input()
stack.append(a)
print(stack)

Python 解法, 执行用时: 10ms, 内存消耗: 2868KB, 提交时间: 2022-08-01

s = [1,2,3,4,5]
s.pop()
print s
s.pop()
print s
i = eval(raw_input())
s.append(i)
print s

上一题