用两个栈实现队列

用两个栈实现队列

public class InterView09_ImplementsQueueByStacks {
	/*题目描述:用两个栈实现队列,完成出队入队功能,若队列空则返回-1
	 * 解体思路:
	 * 声明创建两个栈,stack1(负责入队)、stack2负责出队.
	 * 元素入队时将其放入stack1中
	 * 元素出队时从stack2弹出元素,若stack2为空将stack1中的全部元素弹出放入stack2,若stack1也为空返回-1
	 * */
	public static void main(String[] args) {
		CQueue queue = new CQueue();
		System.out.println(queue.deleteHead());
		queue.appendTail(5);
		queue.appendTail(2);
		System.out.println(queue.deleteHead());
		System.out.println(queue.deleteHead());
	}
}

class CQueue {
	ArrayList<Integer> stack1;
	ArrayList<Integer> stack2;
	int top1;
	int top2;
    public CQueue() {
    	/*初始化过程基于ArrayList创建两个栈
    	 * */
    	stack1 = new ArrayList<Integer>();
    	stack2 = new ArrayList<Integer>();
    	top1=0;
    	top2=0;
    }
    
    public void appendTail(int value) {
    	/*入队函数
    	 *value放入stack1
    	 * */
    	stack1.add(top1, value);
    	top1++;
    }
    
    public int deleteHead() {
    	/*出队函数
    	 *若stack2非空弹出stack2栈顶元素
    	 *若stack2空,stack1全部元素出栈压入stack2,stack2栈顶元素出栈
    	 *若stack2空,stack1空返回-1
    	 * */
    	if(this.top2 != 0) {
    		//若stack2非空弹出栈顶元素
    		top2--;
    		return stack2.remove(top2);
    	}else if(this.top2==0 && this.top1 != 0) {
    		//若stack2空 stack1非空弹出stack1全部元素压入stack2
    		while(top1 !=0) {
    			top1--;
    			int temp = stack1.remove(top1);
    			stack2.add(top2, temp);
    			top2++;
    		}
    		//弹出stack2的栈顶元素
    		top2--;
    		int pop = stack2.remove(top2);
    		return pop;
    	}
    	return -1;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值