做题时发现单链表删除函数调用后无法删除头结点,其他节点可正常删除。
#include<iostream>
using namespace std;
struct Student {
int sno;
char sname[20];
int ssocre;
Student* next;
};
int n;
Student* creat() {//创建链表
Student* head, * p1, * p2;
head = NULL;
p1 = p2 = new Student;
n = 0;
cin >> p1->sno >> p1->sname >> p1->ssocre;
while (p1->sno != -1) {
n = n + 1;
if (n == 1)head = p1;
else p2->next = p1;
p2 = p1;
p1 = new Student;
cin >> p1->sno >> p1->sname >> p1->ssocre;
}
p2->next = NULL;
return head;
}
void Stuprint(Student* head) {//输出链表
Student* p;
p = head;
while (p != NULL) {
cout << p->sno << " " << p->sname << " " << p->ssocre << endl;
p = p->next;
}
}
Student* Sinsert(Student* head) {//插入函数(由于不排序,将插入链表放在最后一个结点)
Student* p0 = NULL, * p1, * p2, * stu;
p1 = head;
stu = new Student;
p0 = stu;
while (p1->next != NULL) {
p2 = p1;
p1 = p1->next;
}
p1->next = p0; p0->next = NULL;
cout << "请输入要插入学生的信息" << endl;
cin >> p0->sno >> p0->sname >> p0->ssocre;
n = n + 1;
return head;
}
struct Student* del(struct Student* head, int num)
{
struct Student* p1, * p2 = NULL;
if (head == NULL)
{
cout << "list null\n"; return NULL;
}
p1 = head;
while (num != p1->sno && p1->next != NULL)
{
p2 = p1; p1 = p1->next;
}
if (num == p1->sno)
{
if (num == head->sno)head = p1->next;
else p2->next = p1->next;
n--;
}
else cout << "无此人\n";
return head;
}
int main() {
Student* head;
cout << "请输入需要录入的学生信息(学号,姓名,成绩,全部输入-1时停止录入)" << endl;
head = creat();
cout << "***************************************************" << endl;
Stuprint(head);
int ans = -1, sno1 = 0;
while (ans) {
cout << "***************************************************" << endl;
cout << "请输入您需要使用的功能(1.删除 2.插入 0.退出程序)" << endl;
cin >> ans;
switch (ans) {
case 1:cout << "请输入需要删除学生的学号" << endl; cin >> sno1; del(head, sno1);
cout << "***************************************************" << endl;
Stuprint(head); break;
case 2:Sinsert(head); cout << "***************************************************" << endl;
Stuprint(head); break;
}
}
return 0;
}
和模板进行了对比,也问了学长和同学
删除函数可以删除所选节点
del函数中删除头结点时修改了del函数中head指针指向的地址 , 你要接收del函数的返回值重新赋值给主函数的head
del(head, sno1) 前面加上 head =
switch (ans) {
case 1:cout << "请输入需要删除学生的学号" << endl; cin >> sno1;
head = del(head, sno1); //前面加上 head =
cout << "***************************************************" << endl;
Stuprint(head); break;
case 2:Sinsert(head); cout << "***************************************************" << endl;
Stuprint(head); break;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!