头文件SeqStack.h
#include<stdio.h> #include<malloc.h> #include<assert.h> #include<stdbool.h> #include<string.h> #define STACK_INIT_SIZE 8 #define INC_SIZE 3 typedef char ElemType; typedef struct SeqStack { ElemType *base; int top; int capacity; }SeqStack; void InitStack(SeqStack *s); void Push(SeqStack *s,ElemType x); bool IsFull(SeqStack *s); bool IsEmpty(SeqStack *s); void Show(SeqStack *s); void Pop(SeqStack *s); bool GetTop(SeqStack *s, ElemType *v); void Clear(SeqStack*s); void Destroy(SeqStack*s); bool inc(SeqStack *s); void Print(SeqStack *s);
函数实现SeqStack.c
#include"SeqStack.h" void InitStack(SeqStack *s) { s->base = (ElemType *)malloc(sizeof(ElemType)* STACK_INIT_SIZE); assert(s->base != NULL); s->capacity = STACK_INIT_SIZE; s->top = 0; } bool IsFull(SeqStack *s) { return s->top >= s->capacity; } bool IsEmpty(SeqStack *s) { return s->top == 0; } void Push(SeqStack *s, ElemType x) { if (IsFull(s)&&!inc(s)) printf("栈空间已满,%d无法继续入栈",x); else s->base[s->top++] = x; } void Show(SeqStack *s) { for (int i = s->top - 1; i >= 0; --i) { printf("%d", s->base[i]); } printf("\n"); } void Pop(SeqStack *s) { if (IsEmpty(s)) { printf("栈空间已空,不能出栈"); } s->top--; } bool GetTop(SeqStack *s, ElemType *v) { if (IsEmpty(s)) { printf("栈空间已满,不能取出栈顶元素"); return false; } else { *v = s->base[s->top - 1]; return true; } } void Clear(SeqStack*s) { s->top = 0; } void Destroy(SeqStack *s) { free(s->base); s->base = NULL;//记住要置为空 s->capacity = 0; s->top = 0; } bool inc(SeqStack *s) {//自增空间函数 ElemType *newbase = (ElemType *)realloc(s->base, sizeof(ElemType)*(s->capacity + INC_SIZE)); if (newbase == NULL) { printf("增配空间失败,内存不足!\n"); return false; } else { s->base = newbase; s->capacity += INC_SIZE; return true; } } void Print(SeqStack *s) { for (int i = 0; i < s->top; ++i) printf("%c ", s->base[i]); }
测试函数Main.c
#include"SeqStack.h" void Convert_8(int value) {//十进制转换为八进制 SeqStack st; InitStack(&st); while (value) { Push(&st, value % 8); value /= 8; } Show(&st); } bool Check(char *str) {//括号匹配 char v; SeqStack st; InitStack(&st); while (*str != '\0') { if (*str == '[' || *str == '(') Push(&st, *str); else if (*str == ']') { GetTop(&st, &v); if (v != '[') return false; Pop(&st); } else if (*str == ')') { GetTop(&st, &v); if (v != '(') return false; Pop(&st); } ++str; } return IsEmpty(&st); } void LineEdit() {//行编辑程序 SeqStack st; InitStack(&st); char ch = getchar(); while (ch != '$') { while (ch != '$'&&ch != '\n') { switch (ch) { case '#': Pop(&st); break; case '@': Clear(&st); break; default: Push(&st, ch); break; } ch = getchar(); } Print(&st); ch = getchar(); } Destroy(&st); } int main() { //char *str = "[([][])]"; //bool flag = Check(str); //if (flag) //printf("括号匹配成功\n"); //else //printf("括号匹配失败\n"); //int value = 47183; //Convert_8(value); LineEdit(); }