DAY9 的KMP过几天发。。等我3号考完试必写完
232.用栈实现队列
这题刷过
class MyQueue {
private:
stack<int> s1;
stack<int> s2;
public:
MyQueue() {
}//先置空?
void push(int x) {
while(s2.empty()==0){
int t=s2.top();
s2.pop();
s1.push(t);
}
s1.push(x);
while(s1.empty()==0){
int t=s1.top();
s1.pop();
s2.push(t);
}
}
int pop() {
while(s2.empty()==0){
int t=s2.top();
s2.pop();
s1.push(t);
}
while(s1.empty()==0){
int t=s1.top();
s1.pop();
s2.push(t);
}
int t=s2.top();
s2.pop();
return t;
}
int peek() {
while(s2.empty()==0){
int t=s2.top();
s2.pop();
s1.push(t);
}
while(s1.empty()==0){
int t=s1.top();
s1.pop();
s2.push(t);
}
return s2.top();
}
bool empty() {
while(s2.empty()==0){
int t=s2.top();
s2.pop();
s1.push(t);
}
while(s1.empty()==0){
int t=s1.top();
s1.pop();
s2.push(t);
}
return s2.empty()==0 ? false : true;
}
};
/**
* 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();
*/
一遍AC了,隐约记得第一次刷的时候看题解发现基本上每个函数之前都会有一个把s1和s2“倒腾”一遍的过程。
class MyQueue {
private:
stack<int> s1;
stack<int> s2;
public:
MyQueue() {
}//先置空?
void push(int x) {
while(s2.empty()==0){
int t=s2.top();
s2.pop();
s1.push(t);
}
s1.push(x);
while(s1.empty()==0){
int t=s1.top();
s1.pop();
s2.push(t);
}
}
int pop() {
int t=s2.top();
s2.pop();
return t;
}
int peek() {
return s2.top();
}
bool empty() {
return s2.empty()==0 ? false : true;
}
};
/**
* 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();
*/
删掉大部分发现也能AC。。。
没啥要说的,下一题
225. 用队列实现栈
class MyStack {
private:
queue<int> q1,q2;//平时就放在q1里,取的时候用q2辅助
public:
MyStack() {}
void push(int x) {
q1.push(x);
}
int pop() {
while(q1.size()!=1){
int t=q1.front();
q1.pop();
q2.push(t);
}
int t=q1.front();
q1.pop();
while(q2.empty()==0){
int f=q2.front();
q2.pop();
q1.push(f);
}
return t;
}
int top() {
while(q1.size()!=1){
int t=q1.front();
q1.pop();
q2.push(t);
}
int t=q1.front();
q1.pop();
q2.push(t);
while(q2.empty()==0){
int f=q2.front();
q2.pop();
q1.push(f);
}
return t;
}
bool empty() {
if(q1.size()!=0) return false;
return true;
}
};
/**
* 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();
*/
AC了
另一个队列是用来备份的,因为把数据在两个队列之间“倒腾”也无法改变“先入先出”的这特点。
就是这里:
int top() {
return que1.back();
}
原来还可以这样写。
好了 栈的part1 over