您的位置:首页 > 职场人生

【刷题】面试题09. 用两个栈实现队列

2020-04-02 18:37 477 查看

用两个栈实现一个队列。队列申明如下,请实现两个函数,appendTail和deleteHead,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead操作返回-1)
因为:队列是先进先出,栈是后进先出,那么将第一个栈的全部数据入栈到第二个栈中,顺序就会变为:后进先出。

class CQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;

public CQueue() {
stack1=new Stack<Integer>();
stack2=new Stack<Integer>();
}

public void appendTail(int value) {
stack1.push(value);
}

public int deleteHead() {
if(stack2.isEmpty()){
if(stack1.isEmpty()){
return -1;
}else{
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}else{
return stack2.pop();
}
}
}
  • 点赞
  • 收藏
  • 分享
  • 文章举报
xiaolu_333 发布了30 篇原创文章 · 获赞 0 · 访问量 469 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: