题解 | NO.42#用两个栈实现队列#3.14
用两个栈实现队列
https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param node int整型
* @return 无
*/
#define Max 1000
//栈1用来入队,栈2用来出队
static int stack1[Max];
static int top1 = -1;
static int stack2[Max];
static int top2 = -1;
//入队即进入栈1
void push(int node ) {
stack1[++top1] = node;
return;
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param 无
* @return int整型
*/
//出队分三种情况
int pop() {
//栈2不空,则出队就是出栈2
if(top2 > -1){
return stack2[top2--];
}
//栈2空,栈1不空,则将栈1元素依次出栈1紧接着入栈2,当栈1空后,出队即出栈2
else if(top1 > -1){
while(top1 > -1){
stack2[++top2] = stack1[top1--];
}
return stack2[top2--];
}
//栈2空,栈1也空,此时队列中没有元素,不能出队,返回-1
else
return -1;
}