题解 | 用两个栈实现队列
用两个栈实现队列
https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param node int整型
* @return 无
*/
static int stack1[1000];//定义一个能存1000个整数的静态数组。static定义全局有效,不会被清空
static int top1=0;
static int stack2[1000];
static int top2=0;
void push(int node ) {
// write code here
stack1[top1++]=node;
top2=0;//当元素没有全部出栈又有新元素入栈时,再次直线此程序top2需置0
for(int i=0;i<top1;i++){
stack2[top2++]=stack1[top1-1-i];//栈:先进后出。将stack1里的元素依次出栈,再依次入栈到stack2,来使第一个入栈stack1的元素在stack2中先出来
}
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param 无
* @return int整型
*/
int pop() {
// write code here
int ans=stack2[top2-1];//stack2出栈
top1=0; //push函数中stack1中的所有元素都已入栈到stack2,此时stack1为空,top1指针指向栈底
top2--;//stack2的元素出栈,top2指针后移一位
for(int i=0;i<top2;i++){
stack1[top1++]=stack2[top2-1-i];//当stack2中的元素还没有完全出栈,又有新元素入栈时,让此时还没出栈的元素返回stack1
}
return ans;
}
