要求建立一个简单链表,它由3个学生数据的结点组成,每个结点包括3个域,分别为学号num、成绩score和next指针域,然后输出各结点中的数据。
时间: 2024-06-12 15:03:24 浏览: 72
#include <iostream>
using namespace std;
struct Student{
int num; // 学号
int score; // 成绩
Student* next; // 指向下一个结点的指针
};
int main() {
Student* head = new Student; // 头结点
head->num = 1;
head->score = 90;
head->next = new Student;
head->next->num = 2;
head->next->score = 80;
head->next->next = new Student;
head->next->next->num = 3;
head->next->next->score = 70;
head->next->next->next = NULL; // 最后一个结点的指针域为NULL
// 遍历链表,输出各结点中的数据
Student* p = head;
while(p != NULL) {
cout << "学号:" << p->num << ",成绩:" << p->score << endl;
p = p->next;
}
// 释放链表中的内存
p = head;
while(p != NULL) {
Student* q = p->next;
delete p;
p = q;
}
return 0;
}
阅读全文