#include<stdio.h>
typedef int datatype;
typedef struct node //鏈棧的定義
{
datatype data;
struct node *next;
}Stacknode,*Linkstack;
Linkstack Init_Linkstack() //鏈棧置空
{
return NULL;
}
int Empty_Linkstack(Linkstack top) //判斷空棧
{
if(top==NULL) return 1;
else return 0;
}
Linkstack Push_Linkstack(Linkstack top,datatype e) //入棧
{
Stacknode *s;
s=malloc(sizeof(Stacknode));
s->data=e;
s->next=top;
top=s;
return top;
}
Linkstack Pop_Linkstack(Linkstack top,datatype *e) //出棧
{
Stacknode *p;
if(top==NULL) {printf("鏈棧爲空棧\n");return NULL;}
else
{
*e=top->data;
p=top;
top=top->next;
free(p);
printf("出棧成功,出棧元素爲%d\n",*e);
return top;
}
}
datatype Gettop_Linkstack(Linkstack top) //取棧頂元素
{
if(top==NULL)return NULL;
else return top->data;
}
Linkstack Creat_Linkstack()
{
int e;
Stacknode *p;
p=Init_Linkstack();
do
{
scanf("%d",&e);
p=Push_Linkstack(p,e);
}while(getchar()!='\n');
return p;
}
void out_Linkstack(Linkstack top) //輸出鏈棧
{
Stacknode *p=top;
if(p==NULL) //排除空鏈棧
{
printf("空鏈表無法輸出\n");
return -1;
}
printf("該鏈棧爲:\n棧頂||");
while(p)
{
printf("%d ",p->data);
p=p->next;
}
printf("||棧底\n");
}
void Num_Linkstack(Linkstack top,datatype e)
{
int i=0;
Stacknode *s;
s=top;
while(s!=NULL)
{
i++;
if(s->data==e)
{
printf("該元素距棧頂第%d位\n",i);
return;
}
s=s->next;
}
printf("鏈棧內不存在該數\n");
}
void Loc_Linkstack(Linkstack top,datatype e)
{
int i=0;
Stacknode *s;
s=top;
while(s!=NULL)
{
i++;
if(i==e)
{
printf("距棧頂位置爲第%d位的元素爲%d\n",i,s->data);
return;
}
s=s->next;
}
printf("鏈棧內不存在該位置\n");
}
Linkstack resort_Linkstack(Linkstack top,datatype e,int m)
{
int i=0;
Stacknode *s;
s=top;
while(s!=NULL)
{
i++;
if(i==e)
{
s->data=m;
out_Linkstack(top);
return top;
}
s=s->next;
}
printf("鏈棧內不存在該位置\n");
return top;
}
int main()
{
int n,m;
datatype e;
Linkstack top;
Stacknode *p;
printf("創建鏈棧\n");
top=Creat_Linkstack();
out_Linkstack(top);
A:
printf("****************************\n");
printf("請數字選擇對鏈棧的操作\n0:結束操作\n1:修改元素\n2:判斷空棧\n3:入棧\n4:出棧\n5:取出棧頂元素\n6:輸出棧\n7:按值查找\n8:按位置查找\n");
printf("****************************\n功能選擇爲:");
scanf("%d",&n);
switch(n)
{
case 0:printf("操作結束\n");return 0;
case 1:
{
printf("請輸入要修改位置:");
scanf("%d",&e);
printf("輸入要修改後的數值:");
scanf("%d",&m);
top=resort_Linkstack(top,e,m);
break;
}
case 2:
{
m=Empty_Linkstack(top);
if(m==1) printf("該鏈棧爲空棧\n");
else printf("該鏈棧不爲空棧\n");
break;
}
case 3:
{
printf("請輸入入棧元素e: ");
scanf("%d",&e);
top=Push_Linkstack(top,e);
out_Linkstack(top);
break;
}
case 4:
{
top=Pop_Linkstack(top,&e);
out_Linkstack(top);
break;
}
case 5:
{
e=Gettop_Linkstack(top);
if(e==NULL) printf("鏈棧爲空棧\n");
else printf("棧頂元素爲%d\n",e);
break;
}
case 6:out_Linkstack(top);break;
case 7:
{
printf("請輸入查找數值:");
scanf("%d",&e);
Num_Linkstack(top,e);
break;
}
case 8:
{
printf("請輸入元素距棧頂位置i:");
scanf("%d",&e);
Loc_Linkstack(top,e);
break;
}
default:printf("選擇錯誤,請重新選擇\n");break;
}
getchar();
printf("請輸入回車繼續");
getchar();
system("cls");
out_Linkstack(top);
goto A;
}