PART ONE——顺序栈的实现
#include "main.h"
int main()
{
init(Sta);
while (1)
{
welcome();
choice();
}
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<Windows.h>
#define STACK_SIZE 3
typedef struct SqStack{
int * base;
int * top;
int stacksize;
}SqStack;
SqStack * Sta = (SqStack *)malloc(sizeof(SqStack));
void init(SqStack * s)
{
s->base = (int *)malloc(sizeof(int) * STACK_SIZE);
if (s->base == NULL)
{
printf("初始化失败,退出程序!\n");
exit(-1);
}
s->top = s->base;
s->stacksize = STACK_SIZE;
}
bool full(SqStack * s)
{
if (s->top - s->base == s->stacksize)
{
return true;
}
return false;
}
bool empty(SqStack * s)
{
if (s->top - s->base == 0)
{
return true;
}
return false;
}
bool push(SqStack * s, int val)
{
if (full(s))
{
int num = s->top - s->base;
int * newbase = (int *)realloc(s->base, (s->stacksize + STACK_SIZE) * sizeof(int));
s->base = newbase;
s->top = s->base + num;
s->stacksize += STACK_SIZE;
}
*s->top++ = val;
return true;
}
int pop(SqStack * s)
{
int val;
if (empty(s))
{
printf("栈为空,无法出栈!\n");
return 0;
}
val = *(--s->top);
return val;
}
void traverse(SqStack * s)
{
if (empty(s))
{
printf("栈为空!\n");
return;
}
int index = 0;
system("cls");
printf("从栈底到栈顶的数据为:");
while (index < s->top - s->base)
{
if (index % 5 == 0)
{
printf("\n");
}
printf("%d\t", s->base[index++]);
}
printf("\n");
}
int turn_len(SqStack * s)
{
return (s->top - s->base);
}
void welcome(void)
{
system("cls");
printf("欢迎使用顺序栈系统!\n");
printf("1.添加数据。\n");
printf("2.删除数据。\n");
printf("3.浏览数据。\n");
printf("4.查看栈大小。\n");
printf("请做出你的选择(q退出):");
}
void choice(void)
{
int val;
int index;
char ch;
ch = getch();
switch (ch)
{
case'1':
system("cls");
printf("请输入你需要添加的数据:\n");
scanf("%d", &val);
if (push(Sta, val))
{
printf("数据压栈成功!\n");
}
system("pause");
break;
case'2':
system("cls");
val = pop(Sta);
printf("数据出栈成功!数据为%d.\n", val);
system("pause");
break;
case'3':
system("cls");
traverse(Sta);
system("pause");
break;
case'4':
system("cls");
printf("顺序栈的栈长为:%d.\n", turn_len(Sta));
system("pause");
break;
case'q':
system("cls");
printf("\n系统已退出!\n");
exit(0);
break;
default:
break;
}
}