顺序表栈的基本操作

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define MAXSIZE 100
typedef int datatype;
/*
  定义结构体,data指存储在栈中的数据
  top 是指向栈顶元素
*/
typedef struct
{
datatype data[MAXSIZE];
int top;
}SeqStack;
/*
  初始化栈,将栈顶置空
*/
SeqStack *Init_SeqStack()
{
SeqStack *s;
s = (SeqStack*)malloc(sizeof(SeqStack));
s->top = -1;
return s;
}


/*判栈空*/
int Empty_SeqStack(SeqStack *s) 
{
if (s->top == -1) return 1;
else return 0;
}
void  push_SeqStack(SeqStack *s, datatype x) 
{
if (s->top == MAXSIZE - 1) printf("对不起,栈已经达到最大容量了");
else 
{
s->top++;
s->data[s->top] = x;
printf("%d-入栈成功\n", x);
}
}


/*出栈*/
void Pop_SeqStack(SeqStack *s, datatype x) 
{
if (Empty_SeqStack(s))  printf("栈空\n");
else
{
x = s->data[s->top];
s->top--;
printf("%d出栈成功 !\n",x);
}

}


/*
   取得栈顶元素
*/
datatype Top_SeqStack(SeqStack *s)
{
if (Empty_SeqStack(s)) return 0;
else
return s->data[s->top];
}


void print_SeqStack(SeqStack *s) {

while (s->top != -1)
{
printf("%d ",s->data[s->top]);
s->top--;
}
}
int main() 
{
SeqStack *s;
datatype x;
int a[5] = {1,2,3,4,5};
int i;
s = Init_SeqStack(); //对栈进行初始化

printf("原数组的中数据是:\n");
for (  i = 0; i < 5; i++) 
{
printf("%d ",a[i]);
}
printf("\n");
//将上面声明的数组进行入栈操作
for(int i = 0; i < 5; i++) 
{
push_SeqStack(s, a[i]);
}
//将上面的入栈的数据进行出栈操作


//  print_SeqStack(s);
//将入栈的数据都出栈
//printf("\n出栈的数据是:");
//for (int i = 0; i <  5; i++)
//{
// Pop_SeqStack(s, a[i]);
//}
//查看出栈之后栈中的数据
  //print_SeqStack(s);
//取得栈顶元素
printf("\n将栈顶元素进行输出:");
x = Top_SeqStack(s);
printf("%d",x);
getch();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值