.按照输入的顺序建立一个链表,每个节点包括:学号、姓名、性别、年龄。直到输入的学号为-1结束。然后输出此链表。然后从键盘上输入一个学生的学号,把此学生的节点删除后再输出链表。(要求建立链表、删除用函数)\n\n6.修改5题的建立链表的函数,要求按照输入的逆序建立链表。其他不变。
时间: 2024-02-17 18:04:40 浏览: 77
好的,我会逐一回答你的问题。
1. 首先,我可以帮你实现一个按照输入顺序建立链表的程序。具体实现方法如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
struct Student {
int id;
string name;
char gender;
int age;
Student* next;
};
Student* createList() {
Student* head = new Student;
Student* p = head;
int id;
while (true) {
cout << "请输入学生的学号(输入-1结束):";
cin >> id;
if (id == -1) break;
Student* q = new Student;
q->id = id;
cout << "请输入学生的姓名:";
cin >> q->name;
cout << "请输入学生的性别(男/女):";
cin >> q->gender;
cout << "请输入学生的年龄:";
cin >> q->age;
p->next = q;
p = q;
}
p->next = nullptr;
return head->next;
}
void printList(Student* head) {
cout << "学号\t姓名\t性别\t年龄" << endl;
while (head != nullptr) {
cout << head->id << "\t" << head->name << "\t" << head->gender << "\t" << head->age << endl;
head = head->next;
}
}
void deleteNode(Student* head, int id) {
Student* p = head;
while (p->next != nullptr) {
if (p->next->id == id) {
Student* q = p->next;
p->next = q->next;
delete q;
break;
}
p = p->next;
}
}
int main() {
Student* head = createList();
printList(head);
int id;
cout << "请输入要删除的学生的学号:";
cin >> id;
deleteNode(head, id);
printList(head);
return 0;
}
```
2. 然后,我可以帮你实现一个删除链表节点的函数 `deleteNode`,具体实现方法如上述代码中的 `deleteNode` 函数。
3. 最后,我可以帮你实现一个按照输入逆序建立链表的程序。具体实现方法如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
struct Student {
int id;
string name;
char gender;
int age;
Student* next;
};
Student* createList() {
int id;
Student* head = nullptr;
while (true) {
cout << "请输入学生的学号(输入-1结束):";
cin >> id;
if (id == -1) break;
Student* p = new Student;
p->id = id;
cout << "请输入学生的姓名:";
cin >> p->name;
cout << "请输入学生的性别(男/女):";
cin >> p->gender;
cout << "请输入学生的年龄:";
cin >> p->age;
p->next = head;
head = p;
}
return head;
}
void printList(Student* head) {
cout << "学号\t姓名\t性别\t年龄" << endl;
while (head != nullptr) {
cout << head->id << "\t" << head->name << "\t" << head->gender << "\t" << head->age << endl;
head = head->next;
}
}
void deleteNode(Student* head, int id) {
Student* p = head;
while (p->next != nullptr) {
if (p->next->id == id) {
Student* q = p->next;
p->next = q->next;
delete q;
break;
}
p = p->next;
}
}
int main() {
Student* head = createList();
printList(head);
int id;
cout << "请输入要删除的学生的学号:";
cin >> id;
deleteNode(head, id);
printList(head);
return 0;
}
```
希望我的回答对你有所帮助!
阅读全文