题解 | 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;
}

全部评论

相关推荐

季桑陌:这怎么看是不是外包啊
点赞 评论 收藏
分享
03-09 20:32
运营
牛客972656413号:成绩管理系统会不会有点太。。。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务