题解 | #用两个栈实现队列#
用两个栈实现队列
https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
/*思路
stackpush 存入1 2 3
stackpop 存入3 2 1
输出 stackpop 最后一个
删除 stackpop 最后一个
再从后将数据放回stackpush
*/
#include <stdio.h>
static int stackpush[10000];
static int stackpop[10000];
int pushnum=0;
int popnum=0;
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param node int整型
* @return 无
*/
void push(int node ) {
// write code here
stackpush[pushnum]=node;
pushnum++;
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param 无
* @return int整型
*/
int pop() {
// write code here
while(pushnum>=0)
{
stackpop[popnum]=stackpush[pushnum];
popnum++;
pushnum--;
}
popnum--;
int result=stackpop[popnum];
//删除
stackpop[popnum]=0;
//初始化
pushnum=0;
popnum--;
//存回stackpush
while(popnum>=0)
{
stackpush[pushnum]=stackpop[popnum];
popnum--;
pushnum++;
}
pushnum--;
popnum++;
return result;
}
查看3道真题和解析