题解 | #用两个栈实现队列#

用两个栈实现队列

https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param node int整型 
 * @return 无
 */
struct List {
    int data;
    struct List* next;
}hand1={-1,NULL},hand2={-1,NULL};//头节点
typedef struct Stack {
    struct List* top;
    struct List* bottom;
}Stack;
static Stack S1 = { &hand1,NULL};//入队栈
static Stack S2 = { &hand2,NULL };//出队栈
void push(int node) {
    // write code here
    struct List* L;
    L = (struct List*)malloc(sizeof(struct List));
    L->data=node;
    L->next=S1.top->next;
    S1.top->next=L;
}
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param 无 
 * @return int整型
 */
 void move(){
    while(S1.top->next!=NULL){
        struct List* L;
        L = (struct List*)malloc(sizeof(struct List));
        L->data=S1.top->next->data;
        L->next=S2.top->next;
        S2.top->next=L;
        L=S1.top->next->next;
        free(S1.top->next);
        S1.top->next=L;
    }
 }
int pop() {
    // write code here
    int r;
    struct List* D;
    if(S2.top->next==NULL){
        move();
    }
    r=S2.top->next->data;
    D=S2.top->next->next;
    free(S2.top->next);
    S2.top->next=D;
    return r;
}

全部评论

相关推荐

自学java狠狠赚一...:骗你点star的,港卵公司,记得把star收回去
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-01 11:47
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务