您的位置:首页 > 其它

顺序表栈的基本操作

2017-12-11 20:08 274 查看
#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();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: