用栈实现队列
leetcode :
Implement Queue using Stacks
Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
Notes:
- You must use only standard operations of a stack -- which means only
push
,
to toppeek/pop from top
,size
,
andis empty
operations are valid. - Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
思路:用两个栈,s1,s2,s2只是为了移动数据用的。
class Queue { public: stack<int> s1,s2; // Push element x to the back of queue. void push(int x) { s1.push(x); } // Removes the element from in front of queue. void pop(void) { //将s1内元素除了最后一个全部移动到s2 while(s1.size()>1) { s2.push(s1.top()); s1.pop(); } //最后一个元素删除 s1.pop(); //将s2内元素全部移动到s1 while(s2.size()>0) { s1.push(s2.top()); s2.pop(); } } // Get the front element. int peek(void) { //将s1内元素除了最后一个全部移动到s2 while(s1.size()>1) { s2.push(s1.top()); s1.pop(); } //保存最后一个元素,然后再移动到s2 int res=s1.top(); s2.push(res); s1.pop(); //将s2内元素全部移动到s1 while(s2.size()>0) { s1.push(s2.top()); s2.pop(); } return res; } // Return whether the queue is empty. bool empty(void) { return s1.empty(); } };
leetcode:
Implement Stack using Queues
Implement the following operations of a stack using queues.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- empty() -- Return whether the stack is empty.
Notes:
- You must use only standard operations of a queue -- which means only
push
,
to backpeek/pop from front
,size
,
andis empty
operations are valid. - Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
- You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
class Stack { public: deque<int> q1,q2; // Push element x onto stack. void push(int x) { q1.push_back(x); } // Removes the element on top of the stack. void pop() { while(q1.size()>1)//将q1数据除了最后一个外,全部移动到q2 { q2.push_back(q1.front()); q1.pop_front(); } q1.pop_front();//删除栈顶元素 while(q2.size()>0)//将q2元素全部移动回到q1 { q1.push_back(q2.front()); q2.pop_front(); } } // Get the top element. int top() { while(q1.size()>1)//将q1数据除了最后一个外,全部移动到q2 { q2.push_back(q1.front()); q1.pop_front(); } //获取栈顶元素,将其移动到q2 int res=q1.front(); q2.push_back(q1.front()); q1.pop_front(); while(q2.size()>0)//将q2元素全部移动回到q1 { q1.push_back(q2.front()); q2.pop_front(); } return res; } // Return whether the stack is empty. bool empty() { return q1.empty(); } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-09-30 06:25:47