Open serendipityApe opened 2 years ago
通过栈实现队列 lettcode上有一道相似的用两个栈实现队列 下面直接放答案吧 答案
通过栈实现队列 lettcode上有一道相似的用两个栈实现队列 下面直接放答案吧
答案
// 添加一个辅助栈来实现队列; class Queue { constructor(){ var A=new Stack(); var B=new Stack(); this.A=A; this.B=B; } enqueue(element) { this.A.push(element); // add new element to the rare } peek() { if(this.A.size()==0 && this.B.size()!=0){ return this.B.peek(); }else if(this.B.size == 0){ return -1; } while(this.A.size() !== 0){ this.B.push(this.A.pop()); } return this.B.peek(); // get the head element } size() { return this.A.size()+this.B.size(); // return count of element } dequeue() { if(this.A.size()==0 && this.B.size()!=0){ return this.B.pop(); }else if(this.B.size == 0){ return -1; } while(this.A.size() !== 0){ this.B.push(this.A.pop()); } return this.B.pop(); // remove the head element } }