2008秋-顺序栈-顺序存储结构的栈

/*---------------------------------------------------------
 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);
}




posted @   emanlee  阅读(612)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示