顺序栈的基本操作

方法一:

#include<stdio.h>
#include<malloc.h>
#define Maxsize 100
typedef int dataType;
typedef struct{
	dataType data[Maxsize];
	int top;
}SeqStack;
//创建顺序栈
SeqStack *createStack(){
	SeqStack *s = (SeqStack*)malloc(sizeof(SeqStack));
	s->top = -1;
	return s;
} 
//判断栈空
int empty(SeqStack *s){
	return s->top == -1;
} 
//判断栈是否满
int full(SeqStack *s){
	return s->top == Maxsize-1;
} 
//进栈
void push(SeqStack *s,dataType x){
	if(full(s))  exit(1);
	s->data[++s->top] = x;
} 
//出栈
void pop(SeqStack *s){
	if(empty(s)) exit(1);
	s->top--;
} 
//取栈顶元素的值
dataType top(SeqStack *s) {
	if(empty(s)) exit(1);
	return s->data[s->top];
}
//取栈的元素个数
int num(SeqStack *s){
	return s->top+1;
}
//遍历整个栈 
void outStack(SeqStack *s){
	for(int i=s->top;i>=0;i--){
		printf("%d ",s->data[i]);
	}
} 
int main()
{
	SeqStack *s = createStack();
	push(s,80);
	push(s,90);
	push(s,70);
	push(s,60);
	pop(s);
	printf("栈顶元素为:");
	printf("%d ",top(s));
	printf("\n");
	printf("当前栈的所有元素为:");
	outStack(s);
}

方法二:

#include<stdio.h>
#define MaxSize 50
typedef int ElemType;

//定义栈结构体
typedef struct
{
ElemType data[MaxSize];
int top;
}SqStack;


//初始化栈
void InitStack(SqStack &S)
{
S.top = -1;
}

//判断栈是否为空
bool StackEmpty(SqStack S)
{
if(S.top == -1)
return true;  //栈为空
else
return false;
}

//入栈
bool Push(SqStack &S,ElemType x)
{
if(S.top == MaxSize-1)
return false;
S.data[++S.top] = x;
return true;
}

//出栈
bool Pop(SqStack &S,ElemType x)
{
if(S.top == -1)
return false;
x = S.data[S.top--];
printf("%d\n",x);
//为查看栈的出栈元素
return true;
}

//获取栈顶元素
bool GetTop(SqStack S,ElemType &x)
{
if(S.top == -1)
return false;
x = S.data[S.top];
printf("%d\n",x);
//为查看栈的栈顶元素
return true;
}


int main()
{
SqStack s;
int m,x;
InitStack(s);
Push(s,3);
Push(s,9);
Push(s,17);
Pop(s,x);
m = StackEmpty(s);
GetTop(s,x);
printf("%d\n",m);
}



  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值