/* create a stack by linllist
*/
#include<stdio.h>
#include<stdlib.h>
struct Stack
{
int value;
struct Stack* next;
};
typedef struct Stack stack;
void menu(void)
{
printf("menu:\n");
printf("1.initialize\n");
printf("2.push\n");
printf("3.pop\n");
printf("4.printtheelements\n");
printf("5.deletethestack\n");
}
int Choice(void)
{
int choice=0;
printf("please input your choice:");
scanf("%d",&choice);
return choice;
}
stack* initialize(void)
{
return NULL;
}
void push(stack** s,int data)
{
stack* newnode=(stack*)malloc(sizeof(stack));
newnode->value=data;
newnode->next=*s;
*s=newnode;
}
int isempty(stack* s)
{
return s==NULL;
}
int pop(stack** s)
{
int data;
stack* temp;
if(isempty(*s))
{
printf("the stack is empty\n");
return 0;
}else
{
temp=*s;
*s=temp->next;
data=temp->value;
free(temp);
return data;
}
}
void printtheelements(stack** s)
{
stack* temp=*s;
printf("the elements are:");
while(temp)
{
printf("%d ",temp->value);
temp=temp->next;
}
}
void deletethestack(stack** s)
{
stack *temp=*s,*prev=*s;
while(prev)
{
temp=prev;
prev=prev->next;
free(temp);
}
free(*s);
*s=NULL;
}
int main()
{
int flag=1,data;
stack* s=NULL;
menu();
while(flag)
{
switch(Choice())
{
case 1:
s=initialize();
break;
case 2:{
printf("please input value:");
scanf("%d",&data);
push(&s,data);
printf("push ok\n");
break;
}
case 3:{
data=pop(&s);
if(data)
printf("the pop is %d\n",data);
break;
}
case 4:{
printtheelements(&s);
break;
}
case 5:{
deletethestack(&s);
printf("the stack has deleted\n");
break;
}
default:{
flag=0;
break;
}
}
}
return 0;
}
栈(链表实现)
最新推荐文章于 2024-09-07 14:37:21 发布