简单的入栈出栈操作,数组实现
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define max 10000
typedef struct snode* stack;
struct snode
{
int data[max];
int top;
};
void push(stack head,int x)//入栈操作
{ if(head->top==max-1)
{
printf("堆栈满了!\n");//入栈要看栈满了没
return;
}
else
{
head->data[++(head->top)]=x;//x放在top上面一个位置 即top+1
return;
}
}
int pop(stack head)//出栈操作,return删除的值,并在栈中删除该值
{ if(head->top==-1)//出栈要看栈空不空,top为-1时,栈则为空
{
printf("栈空!!\n");
return 0;
}
else
return (head->data[(head->top)--]);
}
void print(stack head)
{ int i;
if(head->top==-1)
{printf("栈空!!\n");
return;
}
else
{
for(i=0;i<=head->top;i++)
printf("%d ",head->data[i]);
return ;
}
}
int main()
{ int i=-1,x;
struct snode A;
stack head=A.data ;
do
{printf("输入!");
i++;
scanf("%d",&head->data[i]);
}while(head->data[i]);
head->top=i-1;
printf("入栈操作,请输入加入的元素x\n");
scanf("%d",&x);
push(head,x);
printf("操作后:\n");
print(head);
printf("\n出栈操作\n");
printf("删除的元素为%d\n",pop(head));
printf("操作后:");
print(head);
return 0;
}