mplement 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.
- You must use only standard operations of a queue -- which means only
push to back
,peek/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).
方法1: push() O(1), pop() O(n), peek() O(n) 用两个queue 来实现, 每次pop事后都把q1前边的都推入q2中, 最后一个出列, 然后q1, q2互换, top时候同理, 只是最后一个元素也入列q2.
方法2: push() O(n), pop() O(1), peek() O(1) 用两个queue 来实现, 每次push时候都入列q2, 然后再把q1的元素都一一入列q2直到q1空为止, 然后q1 q2互换. 这样q1内元素的出列顺序和stack中的顺序相同 所以pop 和 top功能就是q1的 poll() 和peek()class MyStack { Queue<Integer> q1 = new LinkedList<Integer>(); Queue<Integer> q2 = new LinkedList<Integer>(); public void push(int x) { q1.offer(x); } // Removes the element on top of the stack. public void pop() { while (q1.size() > 1) { q2.offer(q1.poll()); } q1.poll(); Queue tem = q1; q1 = q2; q2 = tem; } // Get the top element. public int top() { while (q1.size() > 1) { q2.offer(q1.poll()); } int res = q1.peek(); q2.offer(q1.poll()); Queue tem = q1; q1 = q2; q2 = tem; return res; } // Return whether the stack is empty. public boolean empty() { return q1.isEmpty(); } }
class MyStack { Queue<Integer> q1 = new LinkedList<Integer>(); Queue<Integer> q2 = new LinkedList<Integer>(); public void push(int x) { q2.offer(x); while (!q1.isEmpty()) { q2.offer(q1.poll()); } Queue tem = q1; q1 = q2; q2 = tem; } // Removes the element on top of the stack. public void pop() { q1.poll(); } // Get the top element. public int top() { return q1.peek(); } // Return whether the stack is empty. public boolean empty() { return q1.isEmpty(); } }
没有评论:
发表评论