Problem
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 back, peek/pop from front, size, and is 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).
题目
使用队列实现栈的如下操作。
- push(x)——把元素x到堆栈。
- pop()——删除元素堆栈的顶部。
- top()——获得顶级元素。
- empty()——返回栈是否为空。
注意
- 必须只使用队列的标准操作——这意味着只有下面操作是有效的:push队尾,peek/pop对首,size(),是否为空。
- 根据所用编程语言,只要你只使用队列的标准操作,即使本机不支持队列,也可以通过链表或者双端队列来模拟。
- 假设所有的操作是有效的(比如空栈中没有pop和top操作)。
题解
解题思路
题目的要求是使用队列来实现栈 ,有两种思路可以解决
- 一种是使用队首作为栈顶
- 一种是使用队尾作为栈顶
两种思路应该都可以实现,一种是入栈操作会多一些,一种是出栈操作会多一些。这个题目四个函数中两个都是和栈顶元素的操作有关,因此选择用队首作为栈顶。
代码
/**
 * 使用队列来实现栈。
 * <p>使用队列的队首来当做栈顶。
 * @author zhao
 *
 * @param <E>
 */
public class _225_Implement_Stacks_using_Queues {
    Queue<Integer> q = new LinkedList<Integer>();
    // Push element x onto stack.
    public void push(int x) { 
        q.add(x);   
        int n = q.size();
        while (n > 1) {
            n--;
            q.add(q.poll());
        }
    }
    // Removes the element on top of the stack.
    public void pop() {
        q.poll();
    }
    // Get the top element.
    public int top() {
        return q.peek();
    }
    // Return whether the stack is empty.
    public boolean empty() {
        return q.isEmpty();
    }   
}
 
                    
                     
                    
                 
                    
                 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号