数据结构(C语言)之——顺序栈
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef char ElemType;
typedef struct {
ElemType* elems; //存放栈中元素
int top; //栈顶指针
int maxSize; //栈的最大长度
}SqStack;
//创建最大长度为maxSize的栈
SqStack* createStack(int maxSize) {
SqStack* s = (SqStack*) malloc(sizeof(SqStack));
s->elems = (ElemType*) malloc(sizeof(ElemType)*maxSize);
s->top = -1;
s->maxSize = maxSize;
return s;
}
//释放栈
void releaseStack(SqStack* s) {
free(s->elems);
free(s);
}
//入栈操作
bool push(SqStack* s, ElemType e) {
if(s->top == s->maxSize-1) {
//栈满
return false;
}
s->top += 1;
s->elems[s->top] = e;
return true;
}
//出栈操作
ElemType pop(SqStack* s) {
if(s->top == -1) return NULL; //栈空
ElemType e = s->elems[s->top];
s->top -= 1;
return e;
}
//读栈顶元素
ElemType readTop(SqStack* s) {
return s->top == -1 ? NULL : s->elems[s->top];
}
//判断栈空
bool isEmpty(SqStack* s) {
return s->top == -1 ? true : false;
}
//打印栈的所有元素
void printStack(SqStack* s) {
printf("从栈顶至栈底依次输出所有元素值:");
for(int i=s->top; i>=0; i--) printf("%d ", s->elems[i]);
printf("\n");
}
int main() {
SqStack* s = createStack(100);
printf("输入入栈序列(从左至右依次入栈):(如abcdefg):");
char inputStr[100];
scanf("%s", &inputStr);
for(int i=0; i<strlen(inputStr); i++) {
push(s, inputStr[i]);
}
ElemType e;
printf("出栈序列(从左至右依次出栈):");
while(!isEmpty(s)) {
e = pop(s);
printf("%c", e);
}
printf("\n");
releaseStack(s);
return 0;
}
结果:
输入入栈序列(从左至右依次入栈):(如abcdefg):abcdefg
出栈序列(从左至右依次出栈):gfedcba