该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
/*包括初始化栈,判断栈是否为空,出栈,入栈,检查栈顶元素,输出栈内元素*/
#include "stdio.h"
#include "stdlib.h"
#define MAX 1024
struct data
{
int data[MAX];
int top;
};
typedef struct data SEQSTACK;
SEQSTACK *init_seqstack(void) /*初始化栈*/
{
SEQSTACK *head;
head=(SEQSTACK *)malloc(sizeof(SEQSTACK));
if(!head)
return NULL;
else
{
head->top=-1;
return head;
}
}
int empty_seqstack(SEQSTACK *head) /*判断栈是否为空*/
{
if(head->top==-1)
return 0;
else
return 1;
}
int push_seqstack(SEQSTACK *head,int num) /*入栈*/
{
if(head->top==MAX-1)
return 1;
else
{
head->top++;
head->data[head->top]=num;
return 0;
}
}
int pop_seqstack(SEQSTACK *head,int *num) /*出栈*/
{
if(!empty_seqstack(head))
return 1;
else
{
*num=head->data[head->top];
head->top--;
return 0;
}
}
int top_seqstack(SEQSTACK *head) /*栈顶元素*/
{
if(!empty_seqstack(head))
return 0;
else
return head->data[head->top];
}
int print_seqstack(SEQSTACK *head) /*输出栈内元素*/
{
if(!empty_seqstack(head))
return 1;
else
{
int i;
printf("当前栈中的元素:");
for(i=head->top;i>=0;i--)
printf("%d ",head->data[i]);
printf("\n");
return 0;
}
}
int main(void)
{
SEQSTACK *head;
int n,i,num;
head=init_seqstack();
printf("初始化完成!\n");
printf("栈空:%d\n",empty_seqstack(head));
printf("请输入入栈元素个数:");
scanf("%d",&n);
printf("请输入%d个要入栈的元素:",n);
for(i=0;i
{
scanf("%d",&num);
push_seqstack(head,num);
}
print_seqstack(head);
printf("栈顶元素:%d\n",top_seqstack(head));
printf("请输入要出栈的元素个数(不能超过%d个):",n);
scanf("%d",&n);
printf("依次出栈的元素:");
for(i=0;i
{
pop_seqstack(head,&num);
printf("%d ",num);
}
printf("\n");
print_seqstack(head);
printf("栈顶元素:%d\n",top_seqstack(head));
return 0;
}