学生表抽象成一个栈,每个学生(包括姓名、学号、成绩)作为栈中的一个元素,该栈采用顺序存储结构,对该栈进行初始化、输出、入栈、出栈和取栈顶元素基本操作,
时间: 2024-01-26 10:02:45 浏览: 100
定义一个包含学生信息(学号,姓名,成绩)的顺序表
以下是一份C++代码示例:
```C++
#include <iostream>
#include <string.h>
using namespace std;
const int MAXSIZE = 100; // 栈的最大容量
struct Student {
char name[20];
int id;
int score;
};
struct Stack {
Student data[MAXSIZE]; // 栈中存储的元素
int top = -1; // 栈顶指针,初始值为-1
};
void init(Stack& s) {
s.top = -1;
}
bool isEmpty(Stack s) {
return s.top == -1;
}
bool isFull(Stack s) {
return s.top == MAXSIZE - 1;
}
void push(Stack& s, Student x) {
if (isFull(s)) {
cout << "Error: Stack is full!" << endl;
return;
}
s.top++;
s.data[s.top] = x;
}
Student pop(Stack& s) {
if (isEmpty(s)) {
cout << "Error: Stack is empty!" << endl;
Student nullStudent;
nullStudent.id = -1;
return nullStudent;
}
Student x = s.data[s.top];
s.top--;
return x;
}
Student getTop(Stack s) {
if (isEmpty(s)) {
cout << "Error: Stack is empty!" << endl;
Student nullStudent;
nullStudent.id = -1;
return nullStudent;
}
return s.data[s.top];
}
void print(Stack s) {
if (isEmpty(s)) {
cout << "Error: Stack is empty!" << endl;
return;
}
for (int i = s.top; i >= 0; i--) {
cout << "Name: " << s.data[i].name << ", ID: " << s.data[i].id << ", Score: " << s.data[i].score << endl;
}
}
int main() {
Stack s;
init(s);
Student s1 = {"Alice", 1001, 90};
Student s2 = {"Bob", 1002, 85};
Student s3 = {"Charlie", 1003, 95};
push(s, s1);
push(s, s2);
push(s, s3);
print(s);
Student topStudent = getTop(s);
cout << "Top student: " << topStudent.name << ", ID: " << topStudent.id << ", Score: " << topStudent.score << endl;
Student poppedStudent = pop(s);
cout << "Popped student: " << poppedStudent.name << ", ID: " << poppedStudent.id << ", Score: " << poppedStudent.score << endl;
print(s);
return 0;
}
```
该程序定义了一个结构体`Student`,包括姓名、学号、成绩三个字段。另外,还定义了一个结构体`Stack`,其中包括一个数组`data`以及栈顶指针`top`。函数`init`用于初始化栈,函数`isEmpty`和`isFull`用于判断栈是否为空或已满,函数`push`用于将元素入栈,函数`pop`用于将栈顶元素出栈并返回,函数`getTop`用于返回栈顶元素,函数`print`用于遍历栈并输出其中的元素。在`main`函数中,我们创建了三个学生对象,并将它们依次入栈。然后输出整个栈,取出栈顶元素并输出,将栈顶元素出栈并输出,最后再次输出整个栈。
阅读全文