栈的代码详情
双栈队列代码
代码
/**
* 双栈队列
* @author 焦焱
*
*/
public class TwoStackQueue {
private LinkStack t1 = new LinkStack();
private LinkStack t2 = new LinkStack();
private int size=0;
public int getSize() {
return size;
}
/**
* 入队
* @param val 数据
*/
public void push(int val) {
t2.push(val);
size++;
}
/**
* 出队
* @return 数据
*/
public int pop() {
if(isEmpty())
{
return -1;
}
int re = -1;
//先将t2中的数据全部弹出压入t1
while(!t2.isEmpty())
{
t1.push(t2.pop() );
}
//t1弹出数据
re = t1.pop();
size--;
//重新将t1的压入t2
while(!t1.isEmpty())
{
t2.push(t1.pop());
}
return re;
}
/**
* 获得队顶元素
* @return 数据
*/
public int getTop() {
//和队相同,只不过将pop改为getTop即可
if(isEmpty())
{
return -1;
}
int re = -1;
while(!t2.isEmpty())
{
t1.push(t2.pop());
}
re = t1.getTop();
while(!t1.isEmpty())
{
t2.push(t1.pop());
}
return re;
}
/**
* 显示所有数据
*/
public void show() {
while(!t2.isEmpty())
{
t1.push(t2.pop());
}
while(!t1.isEmpty())
{
//这块注意不能pop要用getTop
System.out.print(t1.getTop()+" ");
t2.push(t1.pop());
}
}
/**
* 判断队是否为空
* @return
*/
public boolean isEmpty() {
return t2.isEmpty();
}
}
测试
public static void main(String[] args) {
TwoStackQueue t = new TwoStackQueue();
for (int i = 0; i < 10; i++) {
t.push(i);
}
t.show();
System.out.println(t.isEmpty());
for (int i = 0; i < 10; i++) {
System.out.print(t.pop() +" ");
}
结果
0 1 2 3 4 5 6 7 8 9 false
0 1 2 3 4 5 6 7 8 9