adding the queue stack problems

This commit is contained in:
Jidong Xiao
2023-11-09 15:34:18 -05:00
parent 8ae5a3c08a
commit 151f59ee5d
3 changed files with 94 additions and 0 deletions

View File

@@ -164,3 +164,5 @@ but requires more work to get right.
- [Leetcode problem 1451: Rearrange Words in a Sentence](https://leetcode.com/problems/rearrange-words-in-a-sentence/). Solution: [p1451_rearrange_words_in_a_sentence.cpp](../../leetcode/p1451_rearrange_words_in_a_sentence.cpp).
- [Leetcode problem 508: Most Frequent Subtree Sum](https://leetcode.com/problems/most-frequent-subtree-sum/). Solution: [p508_most_frequent_subtree_sum.cpp](../../leetcode/p508_most_frequent_subtree_sum.cpp).
- [Leetcode problem 225: Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/). Solution: [p225_stack_using_queues.cpp](../../leetcode/p225_stack_using_queues.cpp).
- [Leetcode problem 232: Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/). Solution: [p232_queue_using_stacks.cpp](../../leetcode/p232_queue_using_stacks.cpp).

View 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();
*/

View 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();
*/