D_S 顺序栈的基本操作

//  main.cpp

#include <iostream>

using namespace std;

#include "Status.h"

typedef int SElemType;

#include "SqStack.h"

 

int main()

{

    SqStack S;

    SElemType e;

    InitStack(S);

    Push(S,2);

    Push(S,4);

    Push(S,6);

    Push(S,8);

    cout<<"\n由栈底至栈顶的元素为:";

    StackTraverse(S);

    cout<<"\n栈的长度为:"<<StackLength(S)<<endl;

    GetTop(S,e);

    cout<<"\n栈顶元素为:"<<e<<endl;

    Pop(S,e);

    cout<<"\n由栈底至栈顶的元素为:";

    StackTraverse(S);

    cout<<"\n栈的长度为:"<<StackLength(S)<<endl;

    GetTop(S,e);

    cout<<"\n栈顶元素为:"<<e<<endl;

    return 0;

}

 

 

 

 

 

 

//  Status.h

#ifndef yuan_Status_h

#define yuan_Status_h

 

#define TRUE 1

#define FALSE 0

#define OK 1

#define ERROR 0

#define INFEASIBLE -1

#define OVERFLOW -2

typedef int Status;

 

#endif

 

 

//  SqStack.h

#ifndef Y_Y_SqStack_h

#define Y_Y_SqStack_h

 

#define MAXSIZE 100

typedef struct{

    SElemType *base;

    SElemType *top;

    int stacksize;

}SqStack;

 

Status InitStack(SqStack &S)

{

    S.base=new SElemType[MAXSIZE];  //为顺序栈分配一个最大容量为MAXSIZE的数组空间

    if(!S.base)  exit(OVERFLOW);

    S.top=S.base;

    S.stacksize=MAXSIZE;

    return OK;

}

 

Status Push(SqStack &S,SElemType e)

{

    if (S.top-S.base==S.stacksize) return ERROR;  //满栈

    *S.top++=e;  //元素e压入栈顶,栈顶指针加1

    return OK;

}

 

Status Pop(SqStack &S,SElemType &e)

{

    if(S.top==S.base) return ERROR;  //空栈

    e=*--S.top;  //栈顶指针减1,将栈顶元素赋给e

    return OK;

}

 

Status StackLength(SqStack S)

{

    return (int)(S.top-S.base);

}

 

Status GetTop(SqStack S,SElemType e)

{

    if (S.top==S.base) exit(1);

    return *(S.top-1);  //栈顶指针减1,返回栈顶元素

}

 

void StackTraverse(SqStack S)

{

    SElemType *p;

    p=S.base;

    while(p!=S.top)

    {

        cout<<*p++<<"  ";

    }

    cout<<endl;

}

 

#endif

 

posted @ 2015-12-02 23:10  Yuan_Ye  阅读(657)  评论(0编辑  收藏  举报