【Java】面试题9:用两个栈实现队列+用两个队列实现栈

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

题目:用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入节点和在队列头部删除节点的功能。

首先定义两个栈:

		Stack<Integer> stack1 = new Stack<Integer>();
		Stack<Integer> stack2 = new Stack<Integer>();

思路:两个栈,有两个端口,那么肯定一个是用来入队的stack1,另一个用来出队的是stack2。同时,由于栈是先进后出的,那么经过两次的入栈则会变为先进先出,即,第一次先进后出,第二次后进先出,两个加起来就变成了先进先出。

故,入队时,
为了保证队中能有序出入,我们先从stack1出栈,进入stack2.

package jianZhiOffer;
import java.util.Stack;
/*
 * 面试题9:用两个栈实现队列
 * 题目:用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead,
 * 分别完成在队列尾部插入节点和在队列头部删除节点的功能。
 */
public class O9ZhanHeDuilie {
	public class Main{
		Stack<Integer> stack1 = new Stack<Integer>();
		Stack<Integer> stack2 = new Stack<Integer>();
		
		//进栈操作
		public void appendTail(int item) {
			stack1.push(item);
		}
		//出栈操作
		public int deleteHead() {
			while(!stack2.isEmpty())
				return stack2.pop();
			while(!stack1.isEmpty())
				stack2.push(stack1.pop());
			return stack2.pop();
		}
	}
	public static void main(String[] args) {
		O9ZhanHeDuilie in = new O9ZhanHeDuilie();
		Main m = in.new Main();
		m.appendTail(1);
		m.appendTail(2);
		m.appendTail(3);
		System.out.println(m.deleteHead());
		m.appendTail(4);
		System.out.println(m.deleteHead());
		m.appendTail(5);
		System.out.println(m.deleteHead());
		System.out.println(m.deleteHead());
		System.out.println(m.deleteHead());
	}

}

题目:用两个队列实现一个栈。栈的声明如下,请实现它的两个函数append和delete,分别完成在栈尾部插入节点和在栈头部删除节点的功能。

package jianZhiOffer;
import java.util.LinkedList;
public class O9DuilieHeZhan {
	
	LinkedList<Integer> queue1 = new LinkedList<Integer>();
	LinkedList<Integer> queue2 = new LinkedList<Integer>();
	
	public void append(int val) {//入队
		queue1.addLast(val);
	}
	public int delete() {//出队
		if(queue1.size()<=1)
			return queue1.poll();
		else {
			while(queue1.size()>1)//队列1中剩下一个数字
				queue2.add(queue1.poll());
		}
		
		while(queue2.size()>0) {
			queue1.add(queue2.poll());
		}
		return queue1.poll();
		
	}
	public static void main(String[] args) {
		O9DuilieHeZhan m = new O9DuilieHeZhan();
		m.append(1);
		m.append(2);
		m.append(3);
		m.append(4);
		System.out.println(m.delete());
		System.out.println(m.delete());
		m.append(5);
		System.out.println(m.delete());
		System.out.println(m.delete());
		System.out.println(m.delete());
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_38361153/article/details/88072473