用两个栈实现一个队列。队列的声明如下,请实现他的两个函数appendTail和deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。
/**
*题目:用两个栈实现一个队列。队列的声明如下,请实现他的两个函数appendTail和deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。
*时间:2015年8月27日09:52:06
*文件:CQueue.java
*作者:cutter_point
*/
package bishi.Offer50.y2015.m08.d27;
import java.util.*;
public class CQueue<T>
{
private Stack<T> stack1;
private Stack<T> stack2;
public CQueue()
{
stack1 = new Stack<T>();
stack2 = new Stack<T>();
}
/**
* 给队列末尾添加一个元素
* @param element
*/
public void appendTail(final T element)
{
stack1.push(element);
}
/**
* 删除队首元素
* @return
* @throws Exception
*/
public T deleteHead() throws Exception
{
T p;
if(stack2.empty()) //如果stack2是空的
{
if(stack1.empty())
{
throw new Exception("队列为空");
}//if
else
{
//把栈1中元素移动到栈2中
while(!stack1.empty())
{
p = stack1.pop();
stack2.push(p);
}//while
}//else
}//if
return stack2.pop();
}
public static void Test(char actual, char expected)
{
if (actual == expected)
System.out.print("Test passed.\n");
else
System.out.print("Test failed.\n");
}
public static void main(String[] args) throws Exception
{
CQueue<Character> queue = new CQueue<Character>(); //我们自定义的队列
//添加三个元素,a,b,c
queue.appendTail('a'); queue.appendTail('b'); queue.appendTail('c');
//看看我们的队列是否是按照队列的方式工作的
char head = queue.deleteHead();
Test(head, 'a');
head = queue.deleteHead();
Test(head, 'b');
queue.appendTail('d');
head = queue.deleteHead();
Test(head, 'c');
queue.appendTail('e');
head = queue.deleteHead();
Test(head, 'd');
head = queue.deleteHead();
Test(head, 'e');
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/cutter_point/article/details/48027381