剑指Offer面试题7用两个栈实现队列(附带用两个队列实现栈)

面试题7:用两个栈实现队列

完成两个函数appendTail和deletedHead,分别是在队列尾部插入节点和在队列头部删除节点的功能。

思路:添加元素即压入一个栈s1,删除元素的话,把s1中的元素按顺序先弹出再压入栈s2中,这是弹出栈s2的元素就能实现先进先出了。

相关题:用两个队列实现栈。

思路:添加元素即向一个队列q1添加元素,删除元素的话,把q1的元素按顺序出队然后入队到q2,最后q1剩下一个元素,就是要出栈的元素,再添加元素的话,向非空的队列添加。

用两个栈实现队列的Java实现:

public class CQueue {
	private Stack<Integer> stack1 = new Stack<>();
	private Stack<Integer> stack2 = new Stack<>();
	
	public void appendTail(int elem){
		//添加元素就直接向stack1添加
		stack1.push(elem);
		System.out.println("stack1:" + stack1.toString());
	}
	public void deleteHead(){
		//删除分三种情况:1,stack2不空,直接从它里头弹出。2,stack2空,stack1不空,把1中先弹再压到2,再从2弹出。3,两都空。
		if(!stack2.isEmpty()){
			stack2.pop();
		}else if(!stack1.isEmpty()){
			while(!stack1.isEmpty()){
				stack2.push(stack1.pop());
			}
			stack2.pop();
		}else{
			System.out.println("两个栈都空了");
		}
		System.out.println("stack1:" + stack1.toString());
		System.out.println("stack2:" + stack2.toString());
	}
	public static void main(String[] args) {
		CQueue test = new CQueue();
		test.appendTail(1);
		test.appendTail(2);
		test.appendTail(3);
		test.deleteHead();
		test.deleteHead();
		test.appendTail(4);
		test.deleteHead();
	}
}

用两个队列实现栈的Java实现:

import java.util.Queue;
import java.util.LinkedList;

//以下是相关题,两个队列实现栈。
public class CStack {
	//是LinkedList类实现了Queue接口
	private static Queue<Integer> queue1 = new LinkedList<>();
	private static Queue<Integer> queue2 = new LinkedList<>();
	
	private void appendTail(int elem){
		//Queue使用时要尽量避免Collection的add()和remove()方法,而是要使用offer()来加入元素,使用poll()来获取并移出元素。
		//它们的优点是通过返回值可以判断成功与否,add()和remove()方法在失败的时候会抛出异常。 
		//如果要使用前端而不移出该元素,使用element()或者peek()方法。
		//这里是向非空的队列里添加值。都为空的话向队列1添加。
		if(!queue2.isEmpty()){
			queue2.offer(elem);
		}else{
			queue1.offer(elem);
		}
		System.out.println("queue1:" + queue1.toString());
		System.out.println("queue2:" + queue2.toString());
	}
	private void deleteHead(){
		//一个表示空队列,一个表示非空队列
		Queue<Integer> emptyQueue = queue1;
		Queue<Integer> notEmptyQueue = queue2;
		if(!emptyQueue.isEmpty()){
			emptyQueue = queue2;
			notEmptyQueue = queue1;
		}
		//除了非空队列的最后一个元素,别的都按顺序移到空队列
		while(notEmptyQueue.size()!=1){
			emptyQueue.offer(notEmptyQueue.poll());
		}
		//删除刚才留下的最后一个元素
		notEmptyQueue.poll();
		
		System.out.println("queue1:" + queue1.toString());
		System.out.println("queue2:" + queue2.toString());
	}

	public static void main(String[] args) {
		CStack test = new CStack();
		test.appendTail(1);
		test.appendTail(2);
		test.appendTail(3);
		test.deleteHead();
		test.appendTail(4);
		test.deleteHead();
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值