use 2 stacks to simulate a queue

class Stack{
private:
int cur = 0;
int elem[2000001];
public:
void push(int n);
int pop();
int peek();
int size();
};

void Stack::push(int n){
elem[cur] = n;
cur++;
}

int Stack::pop(){
cur--;
return elem[cur + 1];
}

int Stack::peek(){
return elem[cur - 1];
}

int Stack::size(){
return cur;
}

class Queue{
private:
Stack s1, s2;
public:
void enqueue(int n);
int dequeue();
int peek();
int size();
};

void Queue::enqueue(int n){
if(s1.size() == 0){
while(s2.size()){
s1.push(s2.pop());
}
}

s1.push(n);
}

int Queue::dequeue(){
if(s2.size() == 0){
while(s1.size()){
s2.push(s1.pop());
}
}
return s2.pop();
}

int Queue::peek(){
if(s2.size() == 0){
while(s1.size()){
s2.push(s1.pop());
}
}

return s2.peek();
}

int Queue::size(){
return s1.size()? s1.size() : s2.size();
}

你可能感兴趣的:(use 2 stacks to simulate a queue)