1. 程式人生 > >C++實現棧的基本操作

C++實現棧的基本操作

#include<iostream>
#include<cstdlib>
#include<malloc.h>
#include<stdio.h>
using namespace std;
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2

#define STACK_INIT_SIZE 100///儲存空間初始分配量
#define STACKINCREMENT 10///儲存空間分配增量
typedef int SElemType;
typedef struct  {
    SElemType *base;
    SElemType *top;
    int stacksize;
}SqStack;
///建立一個空棧
void InitStack(SqStack &S){
    S.base = (SElemType *) malloc(STACK_INIT_SIZE * sizeof(SElemType));
    //S.base = NULL;
    if(!S.base) exit(OVERFLOW);
    S.top = S.base;
    S.stacksize = STACK_INIT_SIZE;
}
///銷燬棧
void DestoryStack(SqStack &S){
    S.top = S.base;
    free(S.base);
    return;
}
///清理棧
void ClearStack(SqStack &S){
    S.top = S.base;
}
///判斷棧是否為空
int StackEmpty(SqStack S){
    if(S.base == S.top)return FALSE;
    return TRUE;
}
///返回棧的長度
int StackLength(SqStack S){
    return S.top-S.base;
}
///得到棧頂元素並由e返回
int GetTop(SqStack &S,SElemType &e){
    if(S.top == S.base) return ERROR;
    e = *(S.top - 1);
    cout<<e<<endl;
    return OK;
}
///插入元素e為新的棧頂元素
int Push(SqStack &S, SElemType &e){
    if(S.top - S.base >= S.stacksize){
        S.base = (SElemType *)realloc
                                  (S.base,(S.stacksize +STACKINCREMENT)*sizeof(SElemType));
        if(!S.base)exit(OVERFLOW);
        S.top = S.base + S.stacksize;
        S.stacksize +=  STACKINCREMENT;
    }
    *S.top++=e;
    return OK;
}
///若棧頂不空,則刪除S的棧頂元素,用e返回。並返回OK,否則返回ERROR
int Pop(SqStack &S,SElemType &e){
    if(S.top == S.base) return ERROR;
    e = *--S.top;
    return OK;
}
///依次呼叫visit()
void StackTraverse(SqStack S,void (*visit)(SqStack S)){
    visit(S);

}
void visit(SqStack S){
    while(S.top!=S.base){
        cout<<*--S.top<<" " ;
    }
}
int main(){
   SqStack S;
   InitStack(S);
   int a;
   int e;
   cout<<"輸入:"<<endl;
   cin>>a;
   while(a != -1){
       Push(S,a);
       cout<<"輸入:"<<endl;
       cin>>a;
   }
   GetTop(S,e);
   StackTraverse(S,visit);
   cout<<"棧頂元素: "<<e<<endl;
   cout<<"棧長:"<<StackLength(S);
}