题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define STACKSIZE 100000 //因为顺序栈分配的内存不够一直不给过,我真的会栓Q
typedef struct
{
int data[STACKSIZE];
int top;
}_stack;
_stack stack;
void Stack_Init(_stack *s)
{
s->top = -1;
}
bool Stack_Null(_stack *s)
{
if(s->top == -1)
{
return 1;
}
else
{
return 0;
}
}
bool Stack_Full(_stack *s)
{
if(s->top == STACKSIZE-1)
{
return 1;
}
else
{
return 0;
}
}
bool Stack_Push(_stack *s,int x)
{
if(Stack_Full(s))
{
return 0;
}
else
{
s->top++;
s->data[s->top] = x;
return 1;
}
}
int Stack_Pop(_stack *s)
{
int x;
if(Stack_Null(s))
{
return 0;
}
else
{
x = s->data[s->top];
s->top--;
return x;
}
}
int Stack_Top(_stack *s)
{
int x;
if(Stack_Null(s))
{
return 0;
}
else
{
x = s->data[s->top];
return x;
}
}
int main() {
int num,x;
char *str = (char*)malloc(6*sizeof(char));
Stack_Init(&stack);
scanf("%d",&num);
for(int i = 0; i < num; i++)
{
scanf("%s",str);
if(!strcmp(str,"push"))
{
scanf("%d",&x);
if(!Stack_Full(&stack))
{
Stack_Push(&stack,x);
}
else
{
printf("error\n");
}
}
if(!strcmp(str,"pop"))
{
if(Stack_Null(&stack))
{
printf("error\n");
}
else
{
printf("%d\n",Stack_Pop(&stack));
}
}
if(!strcmp(str,"top"))
{
if(Stack_Top(&stack) == 0)
{
printf("error\n");
}
else
{
printf("%d\n",Stack_Top(&stack));
}
}
}
return 0;
}
