数据结构——栈(C语言实现)
#include <stdio.h> #include <stdlib.h> #include<string.h> #include<malloc.h> // 栈结构的定义 typedef struct _stack { int size; // 栈存储空间的尺寸 int* base; // 栈基址 int* sp; // 栈顶 } stack; void init(stack* s, int n) { s->base = (int*)malloc(sizeof(int)*n); s->size = n; s->sp = s->base; } void push(stack* s, int val) { if(s->sp - s->base == s->size) { puts("none"); exit(1); } *s->sp++ = val; } int pop(stack* s) { if(s->sp == s->base) { puts("none"); exit(2); } return *--s->sp; } int peek(stack*s) { if(s->sp == s->base) { puts("none"); exit(2); } return *(s->sp-1); } int empty(stack* s) { return s->sp == s->base; } void clean(stack* s) { if(s->base) free(s->base); } int main(void) { stack s; int i,n; int num; char str[30]; init(&s, 1000); while(1) { scanf("%s",str); if(strcmp(str,"push")==0) { scanf("%d",&num); push(&s, num); } else if(strcmp(str,"top")==0) { printf("%d\n", peek(&s)); } else if(strcmp(str,"pop")==0) { printf("%d\n", pop(&s)); } else if(strcmp(str,"clear")==0) { empty(&s); } else if(strcmp(str,"exit")==0) { clean(&s); break; } } return 0; }
数据结构——栈(C语言实现) - yyf的博客 - CSDN博客 https://blog.csdn.net/qq_18860653/article/details/80388025