码迷,mamicode.com
首页 > 其他好文 > 详细

两个栈实现队列 7

时间:2015-03-30 22:59:57      阅读:196      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!