#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;
}
网友评论