首页 > 代码库 > CTCI 3.5
CTCI 3.5
Implement a MyQueue class which implements a queue using two stacks.
/*Use two stacks, when enqueue, first pop all the elements in stack2 on stack1, then push the element onstack1. when dequeue, first pop all elements in stack1 to stack2, then pop an element. Notice that the orderof elements in two stacks are opposite.*/import java.util.*;public class MyQueue { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void enqueue(int key) { while(stack2.isEmpty() == false) { stack1.add(stack2.pop()); } stack1.add(key); } public int dequeue() { while(stack1.isEmpty() == false) { stack2.add(stack1.pop()); } return stack2.pop(); } public static void main(String[] args) { MyQueue mq = new MyQueue(); mq.enqueue(1); mq.enqueue(2); System.out.println(mq.dequeue()); mq.enqueue(3); System.out.println(mq.dequeue()); System.out.println(mq.dequeue()); }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。