做题时发现单链表删除函数调用后无法删除头结点,其他节点可正常删除。
#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;
}
运行结果及报错内容 可正常运行
我的解答思路和尝试过的方法
和模板进行了对比,也问了学长和同学
我想要达到的结果
删除函数可以删除所选节点