题目描述
题目描述:两个栈实现一个队列。请实现队列的两个函数push 和pop,分别完成在队列尾部插入结点和在队列头部删除结点的功能。
规律发现
思路: 栈是一种受限的线性表,其插入和删除操作只能在表的一端进行,该端称为顶端top,最后插入的元素最先删除,即后进先出 队列也是一种受限的线性表,其插入操作只能在队列的尾端进行,其删除操作只能在其前端进行,最先插入的元素最先删除,即先进先出 根据栈的队列这种相似又不同的表示方式,两个栈实现队列的步骤如下: ① 给定两个栈stack1和stack2,stack1用来存放入队列的元素,stack2用来存放即将出队列的队头元素 ② 队列元素插入操作在尾端进行的具体实现是stack1.push(); ③ 队列元素的删除操作在前端进行的具体实现是stack2.pop(); ④ 在删除队列元素时要先判断stack2和stack2是否都为空: 都为空则没有元素可以出队列, 若stack2不为空则直接出栈就是删除队列的队头元素 若stack2为空,stack1不为空,则先执行stack2.push(stack1.pop()),将stack1中的元素输入到stack2中,进行输出
完整代码展示
public class N5 两个栈实现队列 {
Stack< Integer> stack1 = new Stack < Integer> ( ) ;
Stack< Integer> stack2 = new Stack < Integer> ( ) ;
public void push ( int node) {
stack1. push ( node) ;
}
public int pop ( ) {
if ( stack2. isEmpty ( ) ) {
while ( ! stack1. isEmpty ( ) ) {
stack2. push ( stack1. pop ( ) ) ;
}
}
if ( stack2. isEmpty ( ) ) {
throw new RuntimeException ( "NO more node" ) ;
}
return stack2. pop ( ) ;
}
public static void main ( String[ ] args) {
N5 两个栈实现队列 queue = new N5 两个栈实现队列 ( ) ;
queue. push ( 1 ) ;
queue. push ( 2 ) ;
queue. push ( 3 ) ;
System. out. println ( queue. pop ( ) ) ;
System. out. println ( queue. pop ( ) ) ;
queue. push ( 4 ) ;
System. out. println ( queue. pop ( ) ) ;
System. out. println ( queue. pop ( ) ) ;
System. out. println ( queue. pop ( ) ) ;
}
}
运行结果显示
变体:两个队列实现一个栈
思想:
题目描述:两个队列实现一个栈。通过一系列栈的压入和弹出操作来分析用两个队列模拟一个栈的过程,总结骤如下: ① 给定两个队列queue1,queue2用来存放入栈中的元素,queue1作为元素入栈队列; ② 往栈中插入元素时只需要入队列queue1即可; ③ 元素出栈时要先判断queue1是否为空,因为queue1中的元素总是后进来的,后进先出,除了队列中的最后一个元素,将其他元素添加进queue2,queue1的最后一个元素出队 ④ 如果③中queue1队列为空,则除了queue1中的最后一个元素,将queue2中其他元素添加到queue1,然后queue2中的最后一个元素出队
public class N5 两个队列实现栈{
LinkedList< Integer> queue1 = new LinkedList < Integer> ( ) ;
LinkedList< Integer> queue2 = new LinkedList < Integer> ( ) ;
int[ ] x = new int [ 20 ] ;
public void push ( int node) {
queue1. addLast ( node) ;
}
public int[ ] pop ( ) {
if ( queue2. isEmpty ( ) ) {
if ( ! queue1. isEmpty ( ) ) {
while ( queue1. size ( ) > 1 ) {
queue2. addLast ( queue1. removeFirst ( ) ) ;
x[ 1 ] = queue1. removeFirst ( ) ;
}
}
}
if ( queue1. isEmpty ( ) ) {
if ( ! queue2. isEmpty ( ) ) {
while ( queue2. size ( ) > 1 ) {
queue1. addLast ( queue2. removeFirst ( ) ) ;
x[ 2 ] = queue1. removeFirst ( ) ;
}
}
}
if ( queue2. isEmpty ( ) && queue1. isEmpty ( ) ) {
throw new RuntimeException ( "NO more node" ) ;
}
return x;
}
public String toString ( ) {
return this . queue1. toString ( ) + "," + this . queue2. toString ( ) ;
}
public static void main ( String[ ] args) {
N5 两个队列实现栈 s = new N5 两个队列实现栈 ( ) ;
s. push ( 1 ) ;
s. push ( 2 ) ;
s. push ( 3 ) ;
s. push ( 4 ) ;
System. out. println ( s. pop ( ) ) ;
System. out. println ( s. pop ( ) ) ;
s. push ( 5 ) ;
s. push ( 6 ) ;
System. out. println ( s. pop ( ) ) ;
System. out. println ( s. pop ( ) ) ;
System. out. println ( s. pop ( ) ) ;
System. out. println ( s. pop ( ) ) ;
System. out. println ( s. pop ( ) ) ;
}
}