【数据结构】栈结构操作示例

#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<algorithm>

#define MAXLEN 100
using namespace std;

typedef struct{
    char name[10];
    int age;
}DATA;

typedef struct stack{
    DATA data[MAXLEN+1];
    int top;
}StackType;

StackType * STInit(){
    StackType * p;
    if(p=(StackType*)malloc(sizeof(StackType))){
        p->top=0;
        return p;
    }
    return NULL;
}

int STIsEmpty(StackType* s){
    int t;
    t=(s->top==0);
    return t;
}

int STIsFull(StackType * s ){
    int t;
    t=(s->top==MAXLEN);
    return t;    
}

void STClear(StackType * s){
    s->top=0;
} 

void STFree(StackType * s){
    if(s){
        free(s);
    }
}

int PushST(StackType *s , DATA data){
    if((s->top+1)>MAXLEN){
        cout<<"栈溢出!
";
        return 0;
    }
    s->data[++s->top]=data;
    return 1;
}

DATA PopST(StackType * s){
    if(s->top==0){
        cout<<"栈为空!
";
        exit(0); 
    }
    return (s->data[s->top--]);
}

DATA PeekST(StackType * s){
    if(s->top==0){
        cout<<"栈为空!
";
        exit(0);
    }
    return (s->data[s->top]);
}

int main(){
    StackType * stack;
    DATA data1, data;
    
    stack=STInit();
    cout<<"入栈操作:
";
    cout<<"输入姓名 年龄进行操作:
";
    do{
        cin>>data.name>>data.age;
        if(strcmp(data.name,"0")==0){
            break;
        }
        else{
            PushST(stack, data);
        }
    }while(1);
    
    do{
        cout<<"出栈操作:按任意键进行出栈操作:
";
        getchar();
        data1=PopST(stack);
        cout<<"出栈的数据是"<<data1.name<<" "<<data1.age<<endl; 
    }while(1);
    
    STFree(stack);
    
    return 0;
} 
 

  

原文地址:https://www.cnblogs.com/dragonir/p/5008202.html