#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
typedef int Status;
typedef struct snode{
int data;
struct snode* next;
}snode;
typedef struct linkstack{
snode* top;
snode* bottom;
int length;
}linkstack;
Status creat(linkstack* S){//創建一個空棧
S->top=S->bottom=(snode*)malloc(sizeof(snode));
if(!S->top){
printf("申請空間失敗!\n");
return ERROR;
}
S->top->next=NULL;
S->bottom->next=NULL;
S->length=0;
return OK;
}
bool empty(linkstack S){//判斷棧是否爲空
return !S.length;
}
int size(linkstack S){//返回棧的大小
return S.length;
}
Status push(linkstack* S,int e){//元素入棧
snode* newx=(snode*)malloc(sizeof(snode));
if(!newx){
printf("申請空間失敗!\n");
return ERROR;
}
newx->data=e;
newx->next=S->top->next;
S->top->next=newx;
if(!S->length)
S->bottom=S->bottom->next;
S->length++;
return OK;
}
Status pop(linkstack* S){//彈出棧頂元素
if(!S->length){
printf("當前棧已經爲空!\n");
return ERROR;
}
snode* del=S->top->next;
S->top->next=del->next;
free(del);
S->length--;
return OK;
}
Status gettop(linkstack S,int &e){//獲得棧頂元素 存到e中
if(!S.length){
printf("當前棧爲空!\n");
return ERROR;
}
e=S.top->next->data;
return OK;
}
Status show(linkstack S){//輸出當前棧的內容
if(!S.length){
printf("空!\n");
return ERROR;
}
snode* p=S.top->next;
while(p){
printf("%d ",p->data);
p=p->next;
}
printf("\n");
return OK;
}
Status clear(linkstack *S){//清空棧
while(S->top->next)
pop(S);
return OK;
}
Status destroy(linkstack* S){//銷燬當前棧
snode* del;
while(S->top){
del=S->top;
S->top=S->top->next;
free(del);
}
S->top=S->bottom=NULL;
return OK;
}
void menu(){
printf("\t\t\t\t**********鏈棧操作程序**********\n");
printf("\t\toptions:\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請輸入你的選項: ");
}
int main()
{
linkstack S;
creat(&S);
while(1){
menu();
int op;
int n,m;
int e;
scanf("%d",&op);
switch(op){
case 0:{
system("cls");
printf("\t\t\t謝謝您的操作,再見!\n");
exit(0);
break;
}
case 1:{
system("cls");
creat(&S);
printf("\t\t\t搭建成功!\n");
break;
}
case 2:{
system("cls");
printf("\t\t\t請輸入要將幾個元素入棧:");
scanf("%d",&n);
printf("\t\t\t輸入%d個需要入棧的元素:",n);
while(n--){
scanf("%d",&e);
push(&S,e);
}
system("cls");
printf("\t\t元素入棧成功!\n");
break;
}
case 3:{
system("cls");
printf("\t\t\t當前棧的內容爲:\n\t\t\t");
show(S);
break;
}
case 4:{
system("cls");
if(gettop(S,e))
printf("\t\t\t當前棧頂元素爲 %d\n",e);
break;
}
case 5:{
system("cls");
pop(&S);
printf("\t\t\t棧頂元素彈出成功\n");
break;
}
case 6:{
system("cls");
printf("\t\t\t當前棧的元素數目爲%d個\n",size(S));
break;
}
case 7:{
system("cls");
if(empty(S))
printf("\t\t\t當前棧爲空!\n");
else printf("\t\t\t當前棧不爲空!\n");
break;
}
case 8:{
system("cls");
clear(&S);
printf("\t\t\t當前棧已經被清空!");
break;
}
case 9:{
system("cls");
destroy(&S);
break;
}
default:
system("cls");
printf("\t\t你的輸入有誤,請重新輸入!!!\n");
break;
}
printf("\n");
}
return 0;
}