数据结构——栈——C++实现栈及其操作

来源:互联网 发布:淘宝怎样延迟久点收货 编辑:程序博客网 时间:2024/05/22 11:54

C++实现栈的构建和操作

1:栈的结构体定义

2:置空栈

3:判断是否为空栈

4:进栈

5:出栈

6:显示整个栈元素



切记亲力亲为,动手实践写代码

Stack.h

#define MAXSIZE 100typedef int datatype;typedef struct {datatype data[MAXSIZE];int top;      //记录当前栈顶位置       } Stack;//置空栈bool Empty_Stack(Stack &S);//判断栈是否为空bool IsNull(Stack S);//进栈bool PushStack(Stack &S,datatype a);//出栈bool PopStack(Stack &S);//取栈顶元素,不改变栈本身datatype Top_element(Stack S);//显示整个栈bool show(Stack S);


Stack.cpp

#include "Stack.h"#include <iostream>using std::cin;using std::cout;using std::endl;bool Empty_Stack(Stack &S){S.top = -1;return true;}bool IsNull(Stack S){if (S.top >= 0){return true;}return false;}//进栈bool PushStack(Stack &S,datatype a){if (S.top >= MAXSIZE-1)    //溢出检查必不可少{cout<<"Stack Overflow~"<<endl;return false;}S.data[S.top+1] = a;S.top += 1;return true;}//出栈bool PopStack(Stack &S){if (S.top <= 0){cout<<"Stack Underflow~"<<endl;return false;}S.top -= 1;return true;}//取栈顶元素,不改变栈本身datatype Top_element(Stack S){if (IsNull(S)){return S.data[S.top];}else{cout<<"Empty Stack~";return NULL;}}//显示整个栈bool show(Stack S){if (IsNull(S)){for (int i = 0;i <= S.top;++i){cout<<S.data[i]<<" ";}return true;}else{cout<<"Empty Stack~";return false;}}

main.cpp

/***************************************************************************   *  @file       main.cpp   *  @author     MISAYAONE   *  @date       17  may 2017   *  @remark     17  may 2017    *  @theme      Stack C++    ***************************************************************************/  #include "Stack.h"#include <iostream>using namespace std;int main(int argc,char** argv){Stack S;Empty_Stack(S);  //置空栈cout<<"This Stack is Null ?"<<bool(IsNull(S))<<endl;  //判断是否为空栈PushStack(S,2);  //进栈PushStack(S,3);PushStack(S,4);PushStack(S,2);PushStack(S,8);cout<<"The elements are : ";show(S);         //显示整个栈的内容PopStack(S);     //出栈PopStack(S);cout<<"After the Pop, the top element is: ";cout<<Top_element(S);system("pause");return 0;}



原创粉丝点击