順序棧的完整實現
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define STACK_INIT_SIZE 15//棧的初始空間大小
#define STACKINCREMENT 5//棧的追加空間大小
typedef struct MyStruct
{
int* top; //top指標記錄棧頂元素在棧中的位置
int* base; //base指標,始終指向棧底
int stacksize; //當前已分配的儲存空間大小
}SqStack;
void InitStack(SqStack
{
s->base = (int*)malloc(STACK_INIT_SIZE * sizeof(int));//分配int大小的(STACK_INIT_SIZE)個連續儲存空間
if (!(s->base))
{
printf("分配失敗!!\n");
}
else
{
s->top = s->base;
s->stacksize = STACK_INIT_SIZE;
printf("空棧初始化完成!!\n");
}
}
void
{
if (s->top == s->base)
{
printf("棧為空!!\n");
}
else
{
printf("棧非空!!\n");
}
}
int IsFull(SqStack *s)//判斷棧是否已滿
{
if (s->top - s->base == s->stacksize - 1)
{
printf("棧已滿!!\n");
}
else
{
printf("
}
return 0;
}
void PushStack(SqStack *s)//元素入棧
{
//InitStack(s);
int x;
if (s->top - s->base >= s->stacksize)
{
s->base = (int*)realloc(s->base, (s->stacksize + STACKINCREMENT) * sizeof(int));
}
printf("請輸入要入棧的元素:\n");
scanf("%d", &x);
*(s->top) = x;
s->top++;
}
void PopStack(SqStack *s)//元素出棧
{
//InitStack(s);
printf("**********\n");
if (s->top == s->base)
{
printf("判斷: 棧為空,不能操作出棧\n");
}
else
{
int x;
x= *(s->top - 1);//先把top位置上的值賦給x,再讓top往下移動一位
s->top--;
printf("%d 出棧\n", x);
}
}
void GetTop(SqStack *s)//獲取棧頂元素
{
if (s->top > s->base)
{
printf("**********\n");
printf("棧頂元素為:%d\n", *(s->top - 1));
printf("**********\n");
}
else
{
printf("棧為空!!\n");
}
}
void Show(SqStack *s)//該函式用來在元素都完成出棧後進行原來位置列印,對比效果
{
printf("棧中元素原來位置上的值為:");
printf("%d ", *(s->top));
}
void GetLength(SqStack *s)//獲取棧長
{
int size;
size= (s->top) - (s->base);
printf("棧長為:%d\n", size);
}
void Display(SqStack *s)//遍歷棧,從棧底開始遍歷
{
while (s->base <= s->top)
{
printf("%d ", *(s->base++));
}
}
void Menue()
{
SqStack s;
int flag;
printf("\t\t\t**********\n");
printf("\t\t\t1:初始化\n");
printf("\t\t\t2:判斷是否為空\n");
printf("\t\t\t3:判斷是否為滿\n");
printf("\t\t\t4:元素入棧\n");
printf("\t\t\t5:元素出棧\n");
printf("\t\t\t6:取棧頂元素\n");
printf("\t\t\t7:獲取棧長度\n");
printf("\t\t\t8:遍歷棧元素\n");
printf("\t\t\t9:遍歷位置元素\n");
printf("\t\t\t0:退出\n");
printf("\t\t\t**********\n");
printf("請輸入相應的序號操作:\n");
scanf("%d", &flag);
while (1)
{
switch (flag)
{
case1:InitStack(&s);
break;
case 2:IsEmpty(&s);
break;
case 3:IsFull(&s);
break;
case 4:PushStack(&s);
break;
case 5:PopStack(&s);
break;
case 6:GetTop(&s);
break;
case7:GetLength(&s);
break;
case 8:Display(&s);
break;
case 9:Show(&s);
break;
case 0:exit(0);
break;
default:printf("輸入指令有誤!!\n");
break;
}
printf("請輸入相應的序號操作:\n");
scanf("%d", &flag);
}
}
void main()
{
Menue();//主函式呼叫
system("pause");
}