顺序栈的表示与实现

顺序栈是指利用顺序存储结构实现的栈,即用一组连续地址的存储单元依次存放到栈底到栈顶的数据元素。

-----------------------------------------------------------------

1.顺序栈的存储结构:(这里以存储整数为例)

1 typedef struct{
2   ElemType data[MAXSIZE];//为顺序栈分配最大容量的内存
3   int top;  //指向栈顶
4 }SqStack;
View Code

------------------------------------

2.基本操作

1)初始化:

1 void Initstack(SqStack &S)
2 {
3     if(!S.data) exit(-1);   //判断是否成功分配内存,如果S.data为NULL,则分配失败
4     S.top = 0;                //使top为零,指向栈底
5 }
View Code

2)入栈:

1 Status Push(SqStack &S,ElemType e)
2 {
3     if(S.top==MAXSIZE) return ERROR;    //判断是否栈满
4     S.data[S.top++] = e;                         //赋值
5     return OK;
6 }
View Code

3)出栈:

1 Status Pop(SqStack &S)
2 {
3    if(S.top<=0) return ERROR;  //先判断栈是否空了
4    S.top--;                                //指针下移
5    return OK;
6 }
View Code

4)获得栈顶元素:

1 void getTop(SqStack S)
2 {
3     printf("栈顶元素是 %d\n",S.data[S.top-1]);
4 }
View Code

5)遍历(这个大都会用到,不算其基本操作):

1 void traverse(SqStack S)
2 {
3     printf("遍历结果:\n");
4     for(int i=0;i<S.top;i++)
5     {
6         printf("%d ",S.data[i]);
7     }
8     printf("\n");
9 }
View Code

------------------------------------------------------------------

完整代码:

#include<stdio.h>
#include<stdlib.h>

#define MAXSIZE 100
#define ERROR 0
#define OK 1

typedef int Status;
typedef int ElemType;

typedef struct{
  ElemType data[MAXSIZE];//为顺序栈分配最大容量的内存
  int top;  //指向栈顶
}SqStack;

void Initstack(SqStack &S)
{
    if(!S.data) exit(-1);
    S.top = 0;
}

Status Push(SqStack &S,ElemType e)
{
    if(S.top==MAXSIZE) return ERROR;
    S.data[S.top++] = e;
    return OK;
}

Status Pop(SqStack &S)
{
   if(S.top<=0) return ERROR;
   S.top--;
   return OK;
}
void getTop(SqStack S)
{
    printf("栈顶元素是 %d\n",S.data[S.top-1]);
}

void traverse(SqStack S)
{
    printf("遍历结果:\n");
    for(int i=0;i<S.top;i++)
    {
        printf("%d ",S.data[i]);
    }
    printf("\n");
}

int main()
{
    SqStack S;

    Initstack(S);

    int n;
    Push(S,3);
    Push(S,4);
    Push(S,5);
    Push(S,7);
    Push(S,8);
    traverse(S);

    Pop(S);
    Pop(S);
    getTop(S);
    traverse(S);

    return 0;
}
View Code

 

posted @ 2019-10-21 09:20  wwww2  阅读(714)  评论(0编辑  收藏  举报