首页 > 其他 > 详细

两个栈实现队列 7

时间:2015-03-30 22:59:11      阅读:305      评论:0      收藏:0      [点我收藏+]

主要实现从尾部添加字符和从头部删除字符

? ?

从尾部添加直接push进一个stack1即可

? ?

从头部删除,需要先将stack1中的字符压入stack2,然后从stack2弹出,这样顺序才对

? ?

考虑一种情况,先pushab,弹出a,再压入c,再弹出的话要弹出b

? ?

在将stack1的数压入stack2之前要判断stack2中是否为空,如果不为空,要等stack2为空了之后才将stack1中的数压入stack2

? ?

package stackToQueue7;

? ?

import java.util.Stack;

? ?

public class StackToQueue7 {

? ?

Stack<String> stack1 = new Stack<>();

Stack<String> stack2 = new Stack<>();

? ?

void appendTail(String string) {

stack1.push(string);

}

? ?

String deleteHead() throws Exception {

if (stack2.isEmpty()) {

while (!stack1.isEmpty()) {

stack2.push(stack1.pop());

}

? ?

}

if (stack2.isEmpty()) {

throw new Exception("队列为空,不能删除");

}

return stack2.pop();

? ?

}

? ?

public static void main(String[] args) throws Exception {

// TODO Auto-generated method stub

StackToQueue7 stackToQueue7 = new StackToQueue7();

stackToQueue7.appendTail("a");

stackToQueue7.appendTail("b");

System.out.println(stackToQueue7.deleteHead());

stackToQueue7.appendTail("c");

System.out.println(stackToQueue7.deleteHead());

System.out.println(stackToQueue7.deleteHead());

// System.out.println(stackToQueue7.deleteHead());

}

? ?

}

两个栈实现队列 7

原文:http://www.cnblogs.com/keedor/p/4379295.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!