题解 | 【模板】栈

【模板】栈

https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf

#include <stdio.h>
#include<string.h>
#include<stdlib.h>
int stack[1000000] = {0};
    int stack_top = -1;
void push(int stack[1000000], int n) {
    stack_top++;
    stack[stack_top] = n;
    return;
}
void top(int stack[1000000]) {
    if(stack_top==-1){
        printf("error\n");
        return;
    }
    printf("%d\n", stack[stack_top]);
    return;
}
void pop(int stack[1000000]) {
     if(stack_top==-1){
        printf("error\n");
        return;
    }
    printf("%d\n", stack[stack_top]);
    stack_top--;
    return;
}
int main() {

    int n = 0;
    char str1[] = "push";
    char str2[] = "pop";
    char str3[] = "top";
    char arr[6];
    scanf("%d", &n);
    


    for (int i = 0; i < n; i++) {
        scanf("%s\n", arr);
        if (strcmp(arr, str1) == 0) {
            int a;
            scanf("%d", &a);
            push(stack, a);
        }
        if (strcmp(arr, str2) == 0) {
            pop(stack);
        }
        if (strcmp(arr, str3) == 0) {
            top(stack);
        }
    }
    return 0;
}

本题我选择使用数组来表示栈,并定义数组下标stack_top来表示栈顶并初始化为-1;分别定义push、pop、top函数来实现对应的操作;输入相应的字符串后进行比对即可。

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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