标签:
Implement Stack using Queues
问题:
Implement the following operations of a stack using queues.
思路:
使用两个队列来回交替的来pop
我的代码:
class MyStack { Queue<Integer> one = new LinkedList<Integer>(); Queue<Integer> two = new LinkedList<Integer>(); public void push(int x) { if(one.isEmpty()) two.offer(x); else one.offer(x); } // Removes the element on top of the stack. public void pop() { if(one.isEmpty()) { while(two.size() != 1) one.offer(two.poll()); two.poll(); } else { while(one.size() != 1) two.offer(one.poll()); one.poll(); } } // Get the top element. public int top() { if(one.isEmpty()) { while(two.size() != 1) one.offer(two.poll()); int last = two.poll(); one.offer(last); return last; } else { while(one.size() != 1) two.offer(one.poll()); int last = one.poll(); two.offer(last); return last; } } // Return whether the stack is empty. public boolean empty() { return one.isEmpty() && two.isEmpty(); } }
他人代码:
class MyStack { Queue<Integer> q = new LinkedList<Integer>(); // Push element x onto stack. public void push(int x) { q.add(x); } // Removes the element on top of the stack. public void pop() { int size = q.size(); for(int i = 1; i < size; i++) q.add(q.remove()); q.remove(); } // Get the top element. public int top() { int size = q.size(); for(int i = 1; i < size; i++) q.add(q.remove()); int ret = q.remove(); q.add(ret); return ret; } // Return whether the stack is empty. public boolean empty() { return q.isEmpty(); } }
学习之处:
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4580936.html