栈的压入,弹出

题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

# -*- coding:utf-8 -*-
class Solution:
    def IsPopOrder(self, pushV, popV):
        # write code here
        stack = []
        index = 0
        for i in pushV:
            stack.append(i)
            while stack and stack[-1] == popV[index]:
                stack.pop();
                index = index + 1
                
        return True if stack == [] else False
### C++ `std::stack` 的基本操作 C++ 中的 `std::stack` 是一个容器适配器,用于实现这一后进先出(LIFO, Last In First Out)的数据结构。其主要功能包括 (`push`) 和弹 (`pop`) 操作。 #### 操作 `push` `push` 方法用于向顶添加一个新的元素。每次调用此方法时,新元素会被放置在的顶部位置[^1]。 ```cpp #include <iostream> #include <stack> int main() { std::stack<int> s; // 使用 push 将元素中 s.push(10); s.push(20); s.push(30); // 查看当前顶元素 std::cout << "顶元素: " << s.top() << std::endl; // 输出 30 return 0; } ``` #### 弹操作 `pop` `pop` 方法用于移除顶的元素。需要注意的是,该方法仅会移除顶元素而不会返回它的值。如果需要获取被移除的值,则应在调用 `pop` 之前使用 `top()` 获取顶元素。 ```cpp #include <iostream> #include <stack> int main() { std::stack<int> s; // 操作 s.push(10); s.push(20); s.push(30); // 弹前查看顶元素 std::cout << "弹顶元素: " << s.top() << std::endl; // 输出 30 // 执行弹操作 s.pop(); // 弹后再查看顶元素 std::cout << "弹顶元素: " << s.top() << std::endl; // 输出 20 return 0; } ``` #### 完整示例:连续与弹 下面是一个完整的例子,展示如何依次将多个元素并逐步弹出它们: ```cpp #include <iostream> #include <stack> int main() { std::stack<int> s; // 连续 s.push(25); s.push(10); s.push(-1); s.push(5); std::cout << "Pushing {25, 10, -1, 5} on stack in that order:" << std::endl; std::cout << "Stack contains " << s.size() << " elements" << std::endl; // 连续弹 while (!s.empty()) { std::cout << "Popping topmost element: " << s.top() << std::endl; s.pop(); } return 0; } ``` 运行以上程序将会得到如下输出: ``` Pushing {25, 10, -1, 5} on stack in that order: Stack contains 4 elements Popping topmost element: 5 Popping topmost element: -1 Popping topmost element: 10 Popping topmost element: 25 ``` 这段代码展示了如何利用 `push` 和 `pop` 实现对的操作,并验证了遵循 LIFO 特性的行为[^3]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值