您的位置:首页 > 其它

栈的顺序存储的初始化、判断栈空、入栈、出栈、读取栈顶元素、栈置空、求栈长操作

2018-01-15 13:54 316 查看
栈的顺序存储的初始化、判断栈空、入栈、出栈、读取栈顶元素、栈置空、求栈长操作

代码如下:

//栈的顺序存储表示
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define MAXSIZE 100
typedef int ElemType;
typedef struct Node{ //定义栈
ElemType data[MAXSIZE];
int top;
}SeqStack;
void *Init_Stack(SeqStack *&s) //栈的初始化
{
s=(SeqStack*)malloc(sizeof(SeqStack)); //方法一
// s=new SeqStack; 方法二
s->top=-1;
}
int Stack_Empty(SeqStack *s) //当栈空时返回1,否则返回0
{
if(s->top==-1)
return 1;
else
return 0;
}

void Push_Stack(SeqStack *s,ElemType x) //入栈操作,当栈未满的时候入栈
{
if(s->top==MAXSIZE-1)
printf("Stack full\n");
else
{
s->top++;
s->data[s->top]=x;
}
}
void GetTop_Stack(SeqStack *s) //读取栈顶元素操作
{
ElemType x;
if(Stack_Empty(s))
{
printf("Stack empty.\n");
}
else
{
x=s->data[s->top];
printf("%d\n",x);
}
}
ElemType Pop_Stack(SeqStack *s) //出栈操作,若栈不为空则删除栈顶元素
{
ElemType x;
if(Stack_Empty(s)) //判断栈是否为空
{
printf("Stack Empty\n");
return NULL;
}
else
{
x=s->data[s->top];
s->top--;
return x;
}
}
void Clear_Stack(SeqStack *s) //栈置空操作
{
s->top=-1;
}
void Stack_Length(SeqStack *s)
{
printf("stack length is %d\n",s->top+1);
}
int main()
{
SeqStack *s;
Init_Stack(s);
Push_Stack(s,1);
Push_Stack(s,2);
Push_Stack(s,3);
GetTop_Stack(s);
Pop_Stack(s);
GetTop_Stack(s);
Stack_Length(s);
Clear_Stack(s);
Stack_Length(s);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐