/*---------------------------------------------------------
Title: Sequence Stack(顺序栈) 顺序栈-顺序存储结构的栈
请先阅读教材67页, 2.3.2,2.3.3节, 栈的定义及基本运算
(注意以下程序为简化后的,仅供入门学习之用)
----------------------------------------------------------*/
#include<stdio.h>
#include<stdlib.h>
//定义栈的结构
struct stacktype
{
int stack[4];//存放数据元素
int top;//栈顶指针
};
//初始化栈
struct stacktype * InitialStack()
{
struct stacktype * head;
head=(struct stacktype *)malloc(sizeof(struct stacktype ));
head->top=-1;//
return head;
}
//入栈
void PushIntoStack(struct stacktype * head, int value)
{
if(head->top==3)// hard code
printf("Push Failed \n");
else
{
head->top++;//
head->stack[head->top]=value;
}
}
//出栈
void PopFromStack(struct stacktype * head)
{
if(head->top==-1)
printf("Pop Failed \n");
else
{
head->top--;//
}
}
//显示栈中所有元素
void ShowStack(struct stacktype * head)
{
int i;
printf("\nShow all elements in stack:\n");
printf(" Current value of top: %d \n Elements:",head->top);
for(i=0;i<=head->top;i++)
printf(" %d ",head->stack[i]);
}
void main()
{
struct stacktype * head1;
head1=InitialStack();
printf("%d",head1->top);
ShowStack(head1);
PushIntoStack(head1,11);
ShowStack(head1);
PushIntoStack(head1,22);
ShowStack(head1);
PopFromStack(head1);
ShowStack(head1);
}
标签:head,顺序,struct,head1,stacktype,top,printf,2008,顺序存储
From: https://blog.51cto.com/emanlee/8245217