【剑指offer】 用两个栈实现队列 -Java

如有不足,请批评指正

1构建队

import java.util.Stack;

public class MyQueue {
	static Stack<Character> stack1=new Stack<>();
	static Stack<Character> stack2=new Stack<>();
	
	public void enQueue(char ch){
		stack1.push(ch);
		
	}
	public MyQueue(Character[] array){
		for(int i=0;i<array.length;i++)
			enQueue(array[i]);
		
	}
	public MyQueue() {
		// TODO Auto-generated constructor stub
	}
	public void deQueue( ){
		if(stack1.isEmpty()) return;
		while(stack1.isEmpty()==false){
			char ch=stack1.pop();
			stack2.push(ch);
		}
		stack2.pop();
		while(stack2.isEmpty()==false)
		{ char ch=stack2.pop();
		stack1.push(ch);	
		}
		
	}

	public void print(){
		System.out.println("the items in the queue are:");
		if(stack1.isEmpty()) return;
		while(stack1.isEmpty()==false){
			char ch=stack1.pop();
			stack2.push(ch);
			
		}
		//stack2.pop();
		while(stack2.isEmpty()==false)
		{ char ch=stack2.pop();
		System.out.print(ch+" ");
		stack1.push(ch);	
		}
		System.out.println();	
	}
}


2 测试结果:


public class TestMyQueue {
	public static void main(String[] args){
	Character[] array={'A','B','C','D'};
	MyQueue queue=new MyQueue(array);
	queue.print();
	queue.deQueue();
	queue.print();
	queue.enQueue('E');
	queue.print();
	queue.deQueue();
	queue.print();
	queue.deQueue();
	queue.print();
	queue.deQueue();
	queue.print();
	queue.deQueue();
	queue.print();

		

	}

}
实验结果:

the items in the queue are:
A B C D 
the items in the queue are:
B C D 
the items in the queue are:
B C D E 
the items in the queue are:
C D E 
the items in the queue are:
D E 
the items in the queue are:
E 
the items in the queue are:






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值