数据结构--栈的操作

来源:互联网 发布:php英文翻译接口 编辑:程序博客网 时间:2024/06/06 02:03

#include <stdio.h>
#include <stdlib.h>
#define Maxsize 100 /*设顺序表的最大长度为100,可依具体情况分配空间*/
//#define NULL -1
typedef int datatype;

typedef struct

{

       datatype stack[Maxsize];

       int top;/*栈顶指针*/

}SeqStack;//顺序栈类型定义

//构造一个空栈

SeqStack *InitStack()

{

       SeqStack *s;/* s为顺序栈类型变量的指针*/

       s=(SeqStack *)malloc(sizeof(SeqStack));

       if(!s)

       {

              printf("空间不足/n");

              return NULL;

       }

       else

       {

              s->top=-1;

              return s;

       }

}

datatype GetTop(SeqStack *s)

{

       if(s->top == -1)

       {

              printf("/n栈是空的!");

              return 0;

       }

       else

              return s->stack[s->top];

}
 

//入栈

SeqStack *Push(SeqStack *s,datatype x)

{

       if(s->top == Maxsize-1 )

       {

              printf("/n栈是满的!");

              return NULL;

       }

       else

       {

              s->top++;

              s->stack[s->top]=x;

              return s;

       }

}

//出栈

datatype Pop(SeqStack *s)

{

       if(s->top == -1)

       {

              printf("/n栈已经空了!");

              return 0;

       }

       s->top--;

       return s->stack[s->top+1];

}

//判别空栈

datatype SeqStackEmpty(SeqStack *s)

{

       if(s->top ==-1)

       {

              printf("此栈是空栈!");

              return 1;

       }

       else

       {

              printf("此栈不是空栈!");

              return 0;

       }

}

void display(SeqStack *p)

{

       int t ;

       t = p->top;

       if(p->top==-1)

       {

              printf("/n此栈是空的");

       }

       else

              while(t!=-1)

              {

                     printf("%d->",p->stack[t]);

                     t--;

              }

}

int main()

{

       int arr[8]={1,2,3,4,5,6,7,8},i;

       SeqStack *p;

       p=InitStack();

      

       //入栈

      

       for(i=0;i<8;i++)

       Push(p,arr[i]);

      

       //遍历栈

       printf("新栈的元素是: ");

       display(p);

       printf("/n");

      

       //得栈顶元素

       printf("栈顶元素是: ");

       printf("%d",GetTop(p));

       printf("/n");

      

       //判别空栈

       printf("判断是否为空栈?: ");

       SeqStackEmpty(p);

       printf("/n");

      

       //出栈

       printf("出栈元素:");

       printf("%d",Pop(p));

       printf("/n");

       //出栈后的栈里元素是:

       printf("出栈后的栈里元素是: ");

       display(p);

       printf("/n");
 
 return 0;
}