栈简单实现

来源:互联网 发布:哪个软件可以搜高数题 编辑:程序博客网 时间:2024/05/22 23:50

// MyStack.cpp : Defines the entry point for the console application.//#include <iostream>#include <cstdio>#include <cstdlib>#include <cassert>#include <cstring>using namespace std;#define MAXLEN 50// 数据准备typedef struct{char name[10];int age;}DATA;typedef struct stack{DATA data[MAXLEN + 1];int top;}StackType;// initStackType *STInit(){StackType *p = NULL;if(p = (StackType *)malloc(sizeof(StackType))){p->top = 0;return p;}cout<<"malloc error!"<<endl;return NULL;}// Emptyint STIsEmpty(StackType *s){int t;t = (s->top == 0);return t;}// FULLint STIsFull(StackType *s){int t;t = (s->top == MAXLEN);return t;}//  Clearvoid STClear(StackType *s){s->top = 0;}// Freevoid STFree(StackType *s){if(s){free(s);}}// pushint PushST(StackType *s, DATA data){if((s->top + 1) > MAXLEN){cout<<"stack is out!"<<endl;return 0;}s->data[++s->top] = data;return 1;}// popDATA PopST(StackType *s){if(s->top == 0){cout<<"stack is empty!"<<endl;exit(0);}return (s->data[s->top--]);      // 弹出当前元素,top --}// Peek 读取栈顶元素DATA PeekST(StackType *s){if (s->top == 0){cout<<"stack is empty!"<<endl;exit(0);}return (s->data[s->top]);}int main(int argc, char* argv[]){StackType *stack;DATA data, data1;stack = STInit();assert(stack);cout<<"Push: "<<endl;cout<<"enter name age push: "<<endl;do{cin>>data.name;cin>>data.age;if(strcmp(data.name, "0") == 0){break;}else{PushST(stack, data);}} while (1);do{cout<<"Pop"<<endl;getchar();data1 = PopST(stack);cout<<data1.name<<data1.age<<endl;} while (1);STFree(stack);return 0;}

Push: enter name age push: tom 1kang 2lucy 300Poplucy3Popkang2Poptom1Popstack is empty!Process returned 0 (0x0)   execution time : 23.035 sPress ENTER to continue.


原创粉丝点击