数据结构-栈(先进后出表)

//数据结构-栈(先进后出表)
#include<stdio.h>
#define MaxSize 100
typedef char ElemType;
typedef struct
{
 ElemType stack[MaxSize];
 int top;
}stacktype;
//初始化栈
void initstack(stacktype *s)
{
  s->top=-1;
}
//入栈
void push(stacktype *s,ElemType x)
{
 if(s->top==MaxSize)
 {
  printf("The stack is full!/n");
 }
 else
 {
  s->top++;
  s->stack[s->top]=x;
 }
}
//出栈
void pop(stacktype *s)
{
 if(s->top==-1)
 {
  printf("The stack is empty!/n");
 }
 else
 {
  s->top--;
 }
}
//取栈顶元素
ElemType gettop(stacktype *s)
{
 if(s->top==-1)
 {
  printf("The stack is empty!/n");
 }
 else
 {
  return(s->stack[s->top]);
 }
}
//显示栈中元素
void display(stacktype *s)
{
 int i;
 printf("The element in the stack:/n");
 for(i=s->top;i>=0;i--)
 {
  printf("%c/n",s->stack[i]);
 }
 printf("/n");

}
//操作的实现
main()
{
 stacktype *st;
 stacktype s;
 st=&s;
 printf("Init a new stack./n");
 initstack(st);
 printf("Push abc into the stack by turns:/n");
 push(st,'a');
 push(st,'b');
 push(st,'c');
 display(st);
 printf("The first word in the stack is:%c/n",gettop(st));
 printf("Pop one word./n");
 pop(st);
 display(st);


 
}

展开阅读全文

没有更多推荐了,返回首页