adding the queue stack problems
This commit is contained in:
40
leetcode/p225_stack_using_queues.cpp
Normal file
40
leetcode/p225_stack_using_queues.cpp
Normal file
@@ -0,0 +1,40 @@
|
||||
class MyStack {
|
||||
public:
|
||||
MyStack() {
|
||||
|
||||
}
|
||||
|
||||
void push(int x) {
|
||||
que.push(x);
|
||||
int size = que.size();
|
||||
for(int i=0;i<size-1;i++){
|
||||
que.push(que.front());
|
||||
que.pop();
|
||||
}
|
||||
}
|
||||
|
||||
int pop() {
|
||||
int x = que.front();
|
||||
que.pop();
|
||||
return x;
|
||||
}
|
||||
|
||||
int top() {
|
||||
return que.front();
|
||||
}
|
||||
|
||||
bool empty() {
|
||||
return que.empty();
|
||||
}
|
||||
private:
|
||||
std::queue<int> que;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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();
|
||||
*/
|
||||
52
leetcode/p232_queue_using_stacks.cpp
Normal file
52
leetcode/p232_queue_using_stacks.cpp
Normal file
@@ -0,0 +1,52 @@
|
||||
// leetcode 232: implementing queues using stacks
|
||||
|
||||
class MyQueue {
|
||||
public:
|
||||
MyQueue() {
|
||||
|
||||
}
|
||||
|
||||
// push 1
|
||||
// push 2
|
||||
// peek
|
||||
void push(int x) {
|
||||
int size = stack1.size();
|
||||
// move every element in stack1 into stack2
|
||||
for(int i=0;i<size;i++){
|
||||
stack2.push(stack1.top());
|
||||
stack1.pop();
|
||||
}
|
||||
stack1.push(x);
|
||||
// move every element in stack2 into stack1
|
||||
for(int i=0;i<size;i++){
|
||||
stack1.push(stack2.top());
|
||||
stack2.pop();
|
||||
}
|
||||
}
|
||||
|
||||
int pop() {
|
||||
int x = stack1.top();
|
||||
stack1.pop();
|
||||
return x;
|
||||
}
|
||||
|
||||
int peek() {
|
||||
return stack1.top();
|
||||
}
|
||||
|
||||
bool empty() {
|
||||
return stack1.empty();
|
||||
}
|
||||
private:
|
||||
std::stack<int> stack1;
|
||||
std::stack<int> stack2;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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();
|
||||
*/
|
||||
Reference in New Issue
Block a user