CTF-Web安全信息安全专业知识C++

C++实训--栈及其应用

2019-05-20  本文已影响0人  简言之_
#include<iostream>
#include<string>
using namespace std;
struct student
{
    int sno;
    string name;
};

typedef struct stack  //栈的数据结构
{
    student *mat;//学生结构体数组
    int top;
    int size;
}*pstack;

void create_stack(pstack &p, int size)//创建栈
{
    p = new stack();
    p->mat = new student[size];
    p->top = -1;
    p->size = size;
}
bool push(pstack p, student &s)//进栈
{
    if (p->top >= p->size)
        return false;
    p->top++;
    p->mat[p->top] = s;
    return true;
}
bool pop(pstack p, student &s)//出栈
{
    if (p->top == -1)
        return false;
    s = p->mat[p->top];
    p->top--;
    return true;
}
bool top(pstack p, student &s)//读栈顶元素
{
    if (p->top == -1)
        return false;
    s = p->mat[p->top];
    return true;
}
bool stack_is_empty(pstack p)//判断栈空
{
    if (p->top == -1)   return true;
    return false;
}
void freestack(student *s)
{
    delete[]s;
}
int main() {
    stack *s;
    create_stack(s, 10);
    student s1[5] = { {111,"jwta"},{222,"jwtb"},{333,"jwtc"},{444,"jwtd"},{555,"jwte"} };
    cout << "进栈顺序:" << endl;
    for (int i = 0; i < 5; i++) {
        push(s, s1[i]);
        cout << s1[i].sno << " " << s1[i].name << endl;
    }
    cout << endl;
    student s2;
    cout << "出栈顺序:" << endl;
    for (int i = 0; i < 5; i++)
    {
        pop(s, s2);
        cout << s2.sno << " " << s2.name << endl;
    }
    freestack(s->mat);
    system("pause");
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读