帮忙数据结构课程设计代码(C语言)

2024-12-24 14:17:14
推荐回答(1个)
回答1:

#include
#include

struct node /*结点的数据结构*/
{
int a;
} ;

struct Stack /*栈的结构*/
{
struct node *A;
int tos;
int size;
};

init(struct Stack *S,int size) /*栈的初始化*/
{
S->A=(struct node *)malloc(sizeof(struct node)*size);
if(S->A==NULL){printf("out of space");getch();exit(1);}
S->tos=-1;
S->size=size;
}

push(struct Stack *S ,struct node e) /*入栈*/
{
if(S->tos==S->size-1){printf("full");getch();return;}
S->tos++;
S->A[S->tos].a=e.a;
}

pop(struct Stack *S) /*出栈*/
{
if(S->tos==-1){printf("empty stack");getch();return;}
S->tos--;
}

getTop(struct Stack *S) /*将栈的顶结点的值打印出来*/
{
if(S->tos==-1){printf("empty stack");getch();return;}
printf("%d",S->A[S->tos].a);
getch();
}

destroy(struct Stack *S) /*销毁栈*/
{
free(S);
}

main()
{
struct Stack S;
char order;
init(&S,5);

while(1) /*菜单*/
{
loop:
clrscr();
printf("1.push\n"
"2.pop\n"
"3.getTop\n"
"4.quit\n"
);
order=getchar();
switch(order)
{
case '1':mpush(&S);break;
case '2':mpop(&S);break;
case '3':mgetTop(&S);break;
case '4':quit(&S);break;
default :goto loop;
}
}
}

mpush(struct Stack *S) /*调用入栈*/
{
struct node e;
printf("input a integer:");
scanf("%d",&e.a);
push(S,e);
}

mpop(struct Stack *S) /*调用出栈*/
{
pop(S);
}

mgetTop(struct Stack *S) /*调用打印栈顶*/
{
getTop(S);
}

quit(struct Stack *S) /*退出,调用销毁*/
{
destroy(S);
exit(0);
}