队列Queue
先进先出,不允许遍历
queue<T> q;
q.push(ele);//从队尾进入队列
q.pop();//从对头出队列
q.front();//获取队头元素
q.back();//获取队尾元素
q.empty();//判断是否为空
q.size();//队的大小
栈Stack
先进后出,不允许遍历
stack<T> s;
s.push(ele);//从栈顶进栈
s.pop();//从栈顶出栈
s.top();//获取栈顶元素
s.empty();//判断是否为空
s.size();//栈的大小
232.用栈实现队列
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push
、pop
、peek
、empty
):
实现 MyQueue
类:
void push(int x)
将元素 x 推到队列的末尾int pop()
从队列的开头移除并返回元素int peek()
返回队列开头的元素boolean empty()
如果队列为空,返回true
;否则,返回false
class MyQueue {
public:
MyQueue() {
}
void push(int x) {
s1.push(x);
}
int pop() {
while(! s1.empty())
{
s2.push(s1.top());
s1.pop();
}
int result=s2.top();
s2.pop();
while(! s2.empty())
{
s1.push(s2.top());
s2.pop();
}
return result;
}
int peek() {
while(! s1.empty())
{
s2.push(s1.top());
s1.pop();
}
int result=s2.top();
//s2.pop();
while(! s2.empty())
{
s1.push(s2.top());
s2.pop();
}
return result;
}
bool empty() {
return s1.empty();
}
private:
stack<int> s1;
stack<int> s2;
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
自己写的代码复杂了,把一个栈的数据放到另一个栈之后处理之后不需要再拿回来,可以取从一个栈操作,存从一个栈操作,如下代码随想录提供的代码:
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stIn.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
// 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
if (stOut.empty()) {
// 从stIn导入数据直到stIn为空
while(!stIn.empty()) {
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;
}
/** Get the front element. */
int peek() {
int res = this->pop(); // 直接使用已有的pop函数
stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return stIn.empty() && stOut.empty();
}
};
225. 用队列实现栈
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push
、top
、pop
和 empty
)。
实现 MyStack
类:
void push(int x)
将元素 x 压入栈顶。int pop()
移除并返回栈顶元素。int top()
返回栈顶元素。boolean empty()
如果栈是空的,返回true
;否则,返回false
。
class MyStack {
public:
MyStack() {
}
void push(int x) {
q.push(x);
num++;
}
int pop() {
int n = num;
while(--n)
{
q.push(q.front());
q.pop();
}
int result = q.front();
q.pop();
num--;
return result;
}
int top() {
int result;
int n = num;
while(n--)
{
q.push(q.front());
result = q.front();
q.pop();
}
//q.pop();
//num--;
return result;
}
bool empty() {
return q.empty();
}
private:
queue<int> q;
int num = 0;
};
/**
* 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();
*/
并不需要使用两个队列,一个就够了,如上。