赞
踩
class MyQueue { public: stack<int>stkin; stack<int>stkout; MyQueue() { } void push(int x) { stkin.push(x); } int pop() { if(stkout.empty()){// 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据) while(!stkin.empty()){ stkout.push(stkin.top()); stkin.pop(); } } int res = stkout.top();// stOut不为空的时候,取栈顶元素 stkout.pop(); return res; } int peek() { int res = this->pop();// 直接使用已有的pop函数 stkout.push(res);// 因为pop函数弹出了元素res,所以再添加回去 return res; } bool empty() { return stkout.empty() && stkin.empty(); } }; /** * Your MyQueue object will be instantiated and called as such: * MyQueue* obj = new MyQueue(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->peek(); * bool param_4 = obj->empty(); */
type MyQueue struct { stack []int back []int } func Constructor() MyQueue { return MyQueue{ stack:make([]int,0), back:make([]int,0), } } func (this *MyQueue) Push(x int) { this.stack = append(this.stack,x) } func (this *MyQueue) Pop() int { if(len(this.back) == 0){ for len(this.stack)!=0{ val := this.stack[len(this.stack)-1]//取出stack的最后一个元素 this.stack = this.stack[:len(this.stack)-1]//stack尾部去掉一个元素 this.back = append(this.back,val) } } val := this.back[len(this.back)-1] this.back = this.back[:len(this.back)-1] return val } func (this *MyQueue) Peek() int { val := this.Pop() if val == 0{ return 0 } this.back = append(this.back,val) return val } func (this *MyQueue) Empty() bool { return len(this.back) == 0 && len(this.stack)==0 } /** * Your MyQueue object will be instantiated and called as such: * obj := Constructor(); * obj.Push(x); * param_2 := obj.Pop(); * param_3 := obj.Peek(); * param_4 := obj.Empty(); */
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。