单链表建立学生数据表
时间: 2024-06-15 20:06:38 浏览: 12
单链表是一种常见的数据结构,用于存储和操作数据。在建立学生数据表时,可以使用单链表来存储每个学生的信息。
首先,我们需要定义一个学生结构体,包含学生的姓名、学号、年龄等信息。然后,创建一个链表节点结构体,包含一个指向学生结构体的指针和一个指向下一个节点的指针。
接下来,我们可以按照以下步骤来建立学生数据表的单链表:
1. 创建一个头节点,并将头节点的指针指向NULL,表示链表为空。
2. 依次输入学生的信息,创建一个新的节点,并将学生信息存储在节点中。
3. 将新节点插入到链表中,可以选择插入到链表的头部或尾部,也可以根据需要插入到指定位置。
4. 重复步骤2和3,直到所有学生的信息都插入到链表中。
下面是一个示例代码,演示了如何建立学生数据表的单链表:
```c++
#include <iostream>
using namespace std;
// 学生结构体
struct Student {
string name;
int id;
int age;
};
// 链表节点结构体
struct ListNode {
Student data;
ListNode* next;
};
// 在链表尾部插入新节点
void insertNode(ListNode*& head, Student student) {
ListNode* newNode = new ListNode;
newNode->data = student;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
ListNode* curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = newNode;
}
}
// 打印链表中的学生信息
void printList(ListNode* head) {
ListNode* curr = head;
while (curr != NULL) {
cout << "姓名:" << curr->data.name << endl;
cout << "学号:" << curr->data.id << endl;
cout << "年龄:" << curr->data.age << endl;
cout << endl;
curr = curr->next;
}
}
int main() {
ListNode* head = NULL;
// 插入学生信息
Student student1 = {"张三", 1001, 18};
insertNode(head, student1);
Student student2 = {"李四", 1002, 19};
insertNode(head, student2);
Student student3 = {"王五", 1003, 20};
insertNode(head, student3);
// 打印学生信息
printList(head);
return 0;
}
```
这样,就可以通过单链表建立一个学生数据表了。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)