S_Stack.h
#pragma once
#include <stdlib.h>
#include <stdio.h>
//栈数据类型
#define SElemType char
//栈初始大小
#define SSize 5
//栈扩容增量
#define SInc 5
//内存溢出异常
#define OVERFLOW -2
//错误
#define ERROR -1
//栈结构体
typedef struct S_Stack
{
SElemType* base;
SElemType* top;
int StackSize;
} Stack;
//初始化栈
void InitStack(Stack& S);
//判断栈是否为空
bool EmptyStack(Stack S);
//清空栈
void ClearStack(Stack& S);
//销毁栈
void DestroyStack(Stack& S);
//获取栈长度
int StackLength(Stack S);
//获取栈顶地址
SElemType* GetTop(Stack S);
//压栈
void Push(Stack& S, SElemType e);
//弹栈
void Pop(Stack& S, SElemType& e);
//遍历栈元素
void StackTraverse(Stack s, void(*f)(SElemType e));
S_Stack.cpp
#include "S_Stack.h"
#include <stdlib.h>
#include <stdio.h>
//初始化栈
void InitStack(Stack& S) {
S.base = (SElemType*)malloc(SSize * sizeof(SElemType));
if(!S.base) exit(OVERFLOW);
S.top = S.base;
S.StackSize = SSize;
printf("Stack Created,Size:%d Base Address:%p\n",S.StackSize,S.base);
}
//判断栈是否为空
bool EmptyStack(Stack S) {
return S.top == S.base ? true : false;
}
//清空
void ClearStack(Stack& S) {
//只需修改栈顶指针到基地址
S.top = S.base;
}
//销毁栈
void DestroyStack(Stack& S) {
free(S.base);
S.base = S.top = NULL;
S.StackSize = 0;
}
//获取栈长度
int StackLength(Stack S) {
return S.top - S.base;
}
//获取栈顶地址
SElemType* GetTop(Stack S) {
return S.top;
}
//压栈
void Push(Stack& S, SElemType e) {
if (S.top - S.base >= S.StackSize) {
//增加栈容量
SElemType* newPStack = (SElemType*)realloc(S.base,(S.StackSize + SInc) * sizeof(SElemType));
if (!newPStack) exit(OVERFLOW);
S.base = newPStack;//realloc可能会重新分配基地址,top地址也需要重新计算
S.top = S.base + S.StackSize;
S.StackSize += SInc;
printf("Stack Rebuild,Size:%d Base Address:%p\n", S.StackSize, S.base);
}
*S.top++ = e;
}
//弹栈
void Pop(Stack& S, SElemType& e) {
if (EmptyStack(S)) exit(ERROR);
e = *--S.top;
}
//遍历栈元素
void StackTraverse(Stack s, void(*f)(SElemType e)) {
SElemType* P = s.top;
while (P-->s.base)
{
f(*P);
}
}
main.cpp(用于测试)
#include "S_Stack.h"
#include <stdio.h>
#include <string.h>
#define PUSH "push"
#define POP "pop"
#define EXIT "exit"
void PrintElem(SElemType e) {
printf("%c\n",e);
}
int main() {
Stack stack;
InitStack(stack);
char opt[10];
SElemType e;
while (1)
{
gets_s(opt, 10);
if (strcmp(opt,EXIT)==0) {
DestroyStack(stack);
return 0;
}
if (strcmp(opt, PUSH)==0) {
printf("wait for input:");
e = getchar();
getchar();
Push(stack, e);
}else if (strcmp(opt,POP)==0) {
Pop(stack, e);
printf("pop:%c\n", e);
}else {
printf("unknow operation\n");
continue;
}
printf("stack:\n");
StackTraverse(stack, PrintElem);
}
return 0;
}
执行结果:
Stack Created,Size:5 Base Address:00F852F8
push
wait for input:a
stack:
a
push
wait for input:b
stack:
b
a
push
wait for input:c
stack:
c
b
a
push
wait for input:d
stack:
d
c
b
a
push
wait for input:e
stack:
e
d
c
b
a
push
wait for input:f
Stack Rebuild,Size:10 Base Address:00F852F8
stack:
f
e
d
c
b
a
pop
pop:f
stack:
e
d
c
b
a