栈的实现--(C++)

代码如下

#include
#include
#include

using namespace std;
#define MAXLEN 50

struct Data{
    string name;
    int age;
};
struct stack{
    Data data[MAXLEN+1];
    int top;
};
//函数声明
stack* stack_init();
int stack_isEmpty(stack *s);
Data* peekStack(stack *s);
Data* popStack(stack *s);
int pushStack(stack *s,Data data);
int stack_isFull(stack *s);
void stack_clear(stack *s);
void stack_free(stack *s);
int main()
{
    stack *stack;
    Data data,*p_data;
    stack=stack_init();
    cout<<"--入栈--"<while(1){
        cout<<"请输入姓名:";
        cin>>data.name;
        cout<<"请输入年龄:";
        cin>>data.age;
        if(data.age == 0)
            break;
        else
            pushStack(stack,data);
    }
    cout<<"输出栈顶元素:";
    p_data = peekStack(stack);
    cout<<"name:"<name<<"  age:"<age<cout<<"所有元素出栈!!!!"<while(1){
        if(stack->top == 0)
            break;
        p_data=popStack(stack);
        cout<<"name:"<name<<"  age:"<age<if(stack_isEmpty){
        cout<<"栈已空!"<//初始化栈
stack* stack_init()
{
    stack *p;
    if(p = new stack){
        p->top = 0;
        return p;
    }
    return NULL;
}
//判断栈是否为空
int stack_isEmpty(stack *s)
{
    return int(s->top == 0);
}
//判断是否满栈
int stack_isFull(stack *s)
{
    return int(s->top == MAXLEN);
}
//清空栈
void stack_clear(stack *s)
{
    s->top = 0;
}
//释放空间
void stack_free(stack *s)
{
    delete s;
}
//入栈
int pushStack(stack *s,Data data)
{
    if((s->top+1)>MAXLEN){
        cout<<"栈溢出!!"<return 0;
    }
    s->data[++s->top]=data;
    return 1;
}
//出栈
Data* popStack(stack *s)
{
    if(s->top == 0){
        cout<<"亲!栈已经空了!"<exit(0);
    }
    return &(s->data[s->top--]);
}
//查询栈顶元素
Data* peekStack(stack *s)
{
    if(s->top == 0){
        cout<<"栈空了——"<exit(0);
    }
    return &(s->data[s->top]);
}

你可能感兴趣的:(c语言,数据结构)