LinkStack.h
#pragma once
#include <stdlib.h>
#define SElemType char
#define ERROR -1
#define OVERFLOW -2
typedef struct L_Stack
{
SElemType data;
struct L_Stack* next;
}*Stk,Stack;
/**
以链表首部指针作为栈顶指针,所有对栈的修改都会影响指针,所以要使用&传递对指针的引用
*/
bool EmptyStack(Stk S);//判断栈是否为空
void ClearStack(Stk& S);//清空栈
void DestroyStack(Stk& S);//销毁栈
int StackLength(Stk S);//获取栈长度
void Push(Stk& S, SElemType e);//压栈
void Pop(Stk& S, SElemType& e);//弹栈
void StackTraverse(Stk S, void(*f)(SElemType e));//遍历栈
LinkStack.cpp
#include <stdlib.h>
#include <stdio.h>
#include "LinkStack.h"
bool EmptyStack(Stk S) {
return S == NULL ? true : false;
}//判断栈是否为空
void ClearStack(Stk& S) {
Stk stk;
while (!EmptyStack(S))
{
stk = S;
S = S->next;
free(stk);
}
}//清空栈
void DestroyStack(Stk& S) {
ClearStack(S);
}//销毁栈
int StackLength(Stk S) {
int len = 0;
Stk stk=S;
while (stk)
{
++len;
stk = stk->next;
}
return len;
}//获取栈长度
void Push(Stk& S, SElemType e) {
Stk newData = (Stk)malloc(sizeof(Stack));
if (!newData) exit(OVERFLOW);
newData->data = e;
newData->next = S;
S = newData;
}//压栈
void Pop(Stk& S, SElemType& e) {
if (!S) exit(ERROR);
e = S->data;
Stk stk = S;
S = S->next;
free(stk);//对内存进行回收
}//弹栈
void StackTraverse(Stk S, void(*f)(SElemType e)) {
Stk stk=S;
while (stk)
{
f(stk->data);
stk = stk->next;
}
printf("stack size:%d\n", StackLength(S));
}//遍历栈
main.cpp(用于测试)
#include <stdio.h>
#include <string.h>
#include "LinkStack.h"
#define PUSH "push"
#define POP "pop"
#define EXIT "exit"
void PrintElem(SElemType e) {
printf("%c\n", e);
}
int main() {
Stk stack=NULL;
char opt[10];
SElemType e;
while (1)
{
gets_s(opt, 10);
if (strcmp(opt, EXIT) == 0) {
DestroyStack(stack);
StackTraverse(stack, PrintElem);
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;
}