中级农民
- 积分
- 111
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2012-12-25
- 最后登录
- 1970-1-1
|
Java代码:- // Implementing queue using only one stack and recusion
- public class SSQueue {
- private Stack<Integer> stack;
- public SSQueue() {
- this.stack = new Stack<Integer>();
- }
- public void enqueue(int e) {
- this.stack = this.addAtBottom(e, this.stack);
- }
- private Stack<Integer> addAtBottom(int e, Stack<Integer> stack) {
- if (stack == null) {
- return null;
- }
- if (stack.size() == 0) {
- stack.push(e);
- return stack;
- }
- Integer top = stack.pop();
- stack = this.addAtBottom(e, stack);
- stack.push(top);
- return stack;
- }
- public int dequeue() {
- int e = -1;
- e = this.stack.pop();
- return e;
- }
- public boolean isEmpty() {
- boolean isEmpty = false;
- isEmpty = this.stack.isEmpty();
- return isEmpty;
- }
- public int peek() {
- int head = -1;
- int top = this.stack.peek();
- head = top;
- return head;
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- SSQueue myQueue = new SSQueue();
-
- myQueue.enqueue(1);
- myQueue.enqueue(2);
- myQueue.enqueue(3);
- myQueue.enqueue(4);
- myQueue.enqueue(5);
-
- while (!myQueue.isEmpty()) {
- System.out.println(myQueue.dequeue());
- }
- }
- }
复制代码
运行结果:
|
|