题解 | #【模板】栈#梦开始的地方
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define STACK_SIZE 100000
int contents[STACK_SIZE] = {0};
int count = 0;
bool is_empty();
bool is_full();
void pop();
void top();
void push(int n);
int main(){
int cmdn[100000] = {0};
int cmdc[100000] = {0};
int n;
scanf("%d",&n);
for (int i = 0; i < n; i++){
char cmd[5] = {0};
scanf("%s",cmd);
if (strcmp(cmd,"push") == 0){
cmdc[i] = 1;
int num;
scanf("%d",&num);
cmdn[i] = num;
} else if (strcmp(cmd,"pop") == 0){
cmdc[i] = 2;
} else if (strcmp(cmd,"top") == 0){
cmdc[i] = 3;
}
}
for (int i = 0; i < n; i++){
if (cmdc[i] == 1){
push(cmdn[i]);
} else if (cmdc[i] == 2){
pop();
} else if (cmdc[i] == 3){
top();
}
}
}
bool is_empty(){
return count == 0;
}
bool is_full(){
return count == STACK_SIZE;
}
void pop(){
if (is_empty()){
printf("error\n");
} else {
printf("%d\n",contents[--count]);
}
}
void top(){
if (is_empty()){
printf("error\n");
} else {
printf("%d\n",contents[count-1]);
}
}
void push(int n){
if (is_full()){
return;
} else {
contents[count++] = n;
}
}
腾讯云智研发成长空间 246人发布