C++ Stack

C++ Stack基本操作

头文件

#include <stack>

常用成员函数

push(x) // x压入栈顶
top() // 返回栈顶元素的引用
pop() // 弹出栈顶元素
empty() // 栈为空返回true
size() // 返回元素个数

定义stack

stack<储存的类型> 容器名
如:
储存int型数据的栈 stack s;
储存double型数据的栈 stack s;
储存string型数据的栈 stack s;
储存结构体或者类的栈 stack<结构体名> s;

当然也可以定义stack数组:
储存int型数据的栈 stack s[n];
储存double型数据的栈 stack s[n];
等等,n为数组的大小

一个例子

class CQueue {
private:
    stack<int> stack1;
    stack<int> stack2;
public:
    CQueue() {
        
    }
    
    void appendTail(int value) {
        stack1.push(value);
    }
    
    int deleteHead() {
        int temp, ans;
        if(stack2.empty() != true){
            ans = stack2.top();  // pop返回void,应该先top获取元素,再pop掉;
            stack2.pop();
            return ans;
        }
        while(stack1.empty() != true){
            temp = stack1.top();
            stack1.pop();
            stack2.push(temp);
        }

        if(stack2.empty() == true){
            return -1;
        }
        ans = stack2.top();
        stack2.pop();
        return ans;
    }
};

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue* obj = new CQueue();
 * obj->appendTail(value);
 * int param_2 = obj->deleteHead();
 */

Reference

http://c.biancheng.net/view/478.html
https://blog.csdn.net/weixin_52115456/article/details/127595817

posted @ 2023-01-01 17:56  961897  阅读(29)  评论(0编辑  收藏  举报