主菜单:
void Menu()
{
printf("**********************************************\n");
printf("\t\t1.栈的初始化\n");
printf("\t\t2.入栈\n");
printf("\t\t3.出栈\n");
printf("\t\t4.栈的长度\n");
printf("\t\t5.销毁栈\n");
printf("\t\t6.清空栈\n");
printf("\t\t7.栈是否为空\n");
printf("\t\t8.遍历栈\n");
printf("\t\t0.退出\n");
printf("**********************************************\n");
}
注:
1.该栈是以结构体通过top和base两个指针结构成,主要操作在top指针。
2.在销毁栈后,需再次进行栈的初始化操作,否则程序将异常退出。
3.该程序只实现栈的基本操作,具体程序可自行优化。
源码:
#include <stdio.h>
#include<stdlib.h>
#include<conio.h>
#define MAXSIZE 100
struct Node{
int data;
};
typedef struct SNode{
struct Node *base;
struct Node *top;
int stacksize;
}SqStack;
SqStack S;
//顺序栈的初始化
SqStack InitStack(){
SqStack S;
S.base = (struct Node*)malloc(sizeof(struct Node));
// S.base = new SElemType[MAXSIZE];
// if(!S.base)
// return NULL;
S.top = S.base; //栈顶指向栈底指针
S.stacksize = MAXSIZE;
return S;
}
//入栈
void Push(SqStack *S,int e){
if(S->top - S->base == S->stacksize)//栈满
//return 0;
printf("栈已满\n");
S->top->data= e;
S->top++;
//*S.top++ = e;
}
//是否为空
int StackEmpty(SqStack S){
if(S.top == S.base)
return 1;
else
return 0;
}
//栈长度
int StackLength(SqStack S){
return S.top-S.base;
}
//清空栈
void ClearStack(SqStack *S){
if(S->base)
S->top = S->base;
}
//销毁栈
void DestoryStack(SqStack S){
if(S.base){
free(S.base);
S.stacksize=0;
S.base = S.top = NULL;
}
}
//出栈
int Pop(SqStack *S){
if(S->top == S->base)
return;
S->top = --S->top;
return S->top->data;
}
void printStack(SqStack S){
int i=0;
int n = S.top-S.base;
printf("栈的数据为:");
for(i=0;i<n;i++)
{
S.top =--S.top;
printf("%d-",S.top->data);
}
}
void Menu()
{
printf("**********************************************\n");
printf("\t\t1.栈的初始化\n");
printf("\t\t2.入栈\n");
printf("\t\t3.出栈\n");
printf("\t\t4.栈的长度\n");
printf("\t\t5.销毁栈\n");
printf("\t\t6.清空栈\n");
printf("\t\t7.栈是否为空\n");
printf("\t\t8.遍历栈\n");
printf("\t\t0.退出\n");
printf("**********************************************\n");
}
int main()
{
S = InitStack();
int data=0,n=0;
char index;
system("color a0");
while (1)
{
Menu();
int choose = _getch();
switch (choose)
{
case '1':
S = InitStack();
printf("栈已初始化\n");
break;
case '2':
printf("入栈数据:");
scanf("%d",&data);
Push(&S,data);
printf("%d已入栈.",data);
break;
case '3':
data = Pop(&S);
printf("%d已出栈.\n",data);
break;
case '4':
n = StackLength(S);
printf("栈的长度为%d\n",n);
break;
case '5':
DestoryStack(S);
printf("栈已销毁\n");
break;
case '6':
ClearStack(&S);
printf("栈已清空\n");
break;
case '7':
if(StackEmpty(S))
printf("栈为空.\n");
else
printf("栈不为空.\n");
break;
case '8':
printStack(S);
break;
case '0':
exit(0);//退出通讯录系统
}
system("pause");
system("cls");
}
return 0;
}