stack.h
#ifndef stack_h__
#define stack_h__
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef enum boolean {FALSE, TRUE} BOOL;
typedef int ElementType;
typedef struct stack_def{
ElementType* data;
int top;
int sz;
}stack;
void initStack(stack* s, int sz);
BOOL isEmpty(stack s);
BOOL isFull(stack s);
void Pop(stack *s);
void Push(stack* s, ElementType e);
ElementType getTop(stack s);
#endif // stack_h__
stack.c
#include "stack.h"
void initStack(stack* s, int sz){
if (sz < 0){
puts("error:sz < 0");
exit(1);
}
s->sz = sz;
s->data = (ElementType*)malloc(sizeof(ElementType)*s->sz);
s->top = -1;
}
BOOL isEmpty(stack s){
return (BOOL)(s.top==-1);
}
BOOL isFull(stack s){
return (BOOL)(s.top == s.sz);
}
void Pop(stack *s){
if (isEmpty(*s)){
puts("error: Pop stack is empty.");
exit(1);
}
s->top--;
}
void Push(stack* s, ElementType e){
if (isFull(*s)){
puts("error: Push stack is Full.");
exit(1);
}
s->data[++s->top] = e;
}
ElementType getTop(stack s){
if (isEmpty(s)){
puts("error: getTop stack is empty.");
exit(1);
}
return s.data[s.top];
}
main.c
#define MAX_LEN 20
#include "stack.h"
int main(){
char str[MAX_LEN];
stack s;
int i;
printf("输入一个字符串:");
gets(str);
initStack(&s, MAX_LEN);
for (i=0; str[i]; i++){
Push(&s, str[i]);
}
puts("Result:");
while (!isEmpty(s)){
putchar(getTop(s));
Pop(&s);
}
printf("
");
return 0;
}
运行结果: