写个笔记,用作复习。
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
#define MaxSize 100
#define true 1
#define error 0
#define OK 1
#define OVERFLOW -2
typedef int ElemType;
typedef struct { //顺序栈结构(动态)
ElemType* top;
ElemType* base;
int stacksize;
}Sqstack;
int InitStack(Sqstack* s); //初始化(在C语言中,形参和实参是单向传递,但可用指针(*)传递地址,让形参影响实参,达到双向传递)
int EmptyStack(Sqstack* s);
int Push(Sqstack* s,ElemType e); //插入元素(在c++中,可以用(&)引用型参数实现双向传递)
int StackLength(Sqstack* s); //元素长度
int StackPrint(Sqstack* s); //打印元素
int Pop(Sqstack* s); //删除栈顶元素
int DestroyStack(Sqstack* s); //销毁栈
int main()
{
int n;
ElemType e, a;
Sqstack *s;
s = (Sqstack*)malloc(sizeof(Sqstack)); //敲黑板重点!指针要有地址!记住分配地址!
InitStack(s);
printf("请输入插入元素个数:");
scanf("%d", &n);
printf("请输入插入元素:");
for (int i = 0; i < n; i++) {
scanf("%d", &e);
Push(s, e);
}
if (EmptyStack(s) == 1)
printf("**啊!***空表**\n");
printf ("元素长度:%d\n",StackLength(s));
printf("打印元素为:");
StackPrint(s);
printf("\n");
a = Pop(s); //我在这里翻了车,前面Pop(s)没赋值a,导致Pop(s)引用两次,引发错误。
if (a == -2)
printf("栈底溢出!\n");
else
printf("删除栈顶元素为:%d\n", a);
printf("删除后:");
StackPrint(s);
printf("\n");
system("pause");
printf("销毁栈中.........\n");
Sleep(3000);
system("cls");
if (DestroyStack(s) == 1)
printf("销毁成功!");
else
printf("销毁失败!");
return 0;
}
int InitStack(Sqstack* s)
{
s->base = (ElemType*)malloc(sizeof(ElemType) * MaxSize);
if (!s->base)
return error;
s->top = s->base;
s->stacksize = MaxSize;
return OK;
}
int EmptyStack(Sqstack* s)
{
if (s->base == s->top)
return true;
else
return error;
}
int Push(Sqstack* s, ElemType e)
{
if (s->top - s->base >= MaxSize)
return OVERFLOW;
if (!s->base)
return error;
*(s->top) = e;
s->top++;
return OK;
}
int StackLength(Sqstack* s)
{
if (s->base == s->top)
return error;
else
return ((s->top) - (s->base));
}
int StackPrint(Sqstack* s)
{
if (s->base == NULL)
return error;
if (s->base == s->top)
printf("没有元素!");
ElemType* p;
p = s->base;
while (p <(s->top))
{
printf("%d ", *p);
p++;
}
return OK;
}
int Pop(Sqstack* s)
{
ElemType a;
if (s->base == s->top)
return OVERFLOW;
else {
a = *(s->top-1 );
s->top--;
}
return a;
}
int DestroyStack(Sqstack* s)
{
free(s);
s->base = s->top = NULL;
s->stacksize = 0;
return OK;
}