关于字符串的1.17-1.18打卡周日再补,今天先把19号的任务做了~
栈:先进后出
相关接口:
void push(T); //入栈 //T代表任意类型(就是stack容器的类型)
void pop(); //出栈
T top(); //获取栈顶元素
bool empty(); //判断是否为空 为空返回true 否则返回false
int size(); // 统计栈内元素数量
队列:先进先出
empty:检测队列是否为空
size:返回队列中有效元素的个数
front:返回队头元素的引用
back:返回队尾元素的引用
push_back:在队列尾部入队列
pop_front:在队列头部出队列
两个栈,一个做入栈,一个做出栈,形成队列。
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
if (stOut.empty()) {
while (! stIn.empty()) {
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;
}
int peek() {
if (stOut.empty()) {
while (! stIn.empty()) {
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
return result;
}
bool empty() {
if (stIn.empty() && stOut.empty()) return true;
else return false;
}
};
这题用一个队列来实现栈的功能的思想很巧妙,不断将队列的队头元素插入队尾并删除,直到原本最开始的队列队尾元素截止,此时便是所谓的栈顶元素
class MyStack {
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int qSize = que.size() - 1;
while (qSize) {
que.push(que.front());
que.pop();
qSize--;
}
int result = que.front();
que.pop();
return result;
}
int top() {
return que.back();
}
bool empty() {
if (que.empty()) return true;
else return false;
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/