链表删除和显示问题!

smdszgzh 2009-03-14 01:55:15

#include "Student.h"
#include <iostream>
#include <string>
using namespace std;
typedef struct ListNode
{
string sID;
string sName;
string bSex;
double Score[2];
ListNode* pNext;
}Node;

class StudentList
{
Node* pHead;
Node* pNew;
Node* pTail;
public:
StudentList(){pHead=NULL;};
Node* ReadStudent(StudentList &list);
void DeleteStudent();
void ShowStudent(StudentList &list);
Node* SelectStudent();
Node* SearchStudent();
};

void StudentList::ShowStudent(StudentList &list)
{
cout<<"ID "<<"Name "<<"Sex "<<"English "<<"Math"<<endl;
Node* p=pHead;
while(p!=NULL)
{
cout<<p->sID<<" "<<p->sName<<" "<<p->bSex<<" "
<<p->Score[0]<<" "<<p->Score[1]<<endl;
p=p->pNext;
}
}

void StudentList::DeleteStudent()
{
string ID;
cout<<"Please input the student's ID"<<endl;
cin>>ID;
Node* pPre;
Node* p=pHead;
while(p!=NULL)
{
pPre=p;
if(ID==p->sID)//因为学号唯一,所以查找到后直接删除,不用继续查找
{
pPre->pNext=p->pNext;
delete p;
cout<<"删除成功!"<<endl;
return;
}
p=p->pNext;
}
cout<<"不存在些学号的学生纪录"<<endl;
}



不用删除功能可以正常显示,当用了删除功能后就不能正常显示了,报错!
...全文
48 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
不好意思,帮上面代码里的next都改成pNext
  • 打赏
  • 举报
回复

while(p!=NULL)
{
pPre=p;
if(ID==p->sID)//因为学号唯一,所以查找到后直接删除,不用继续查找
{
pPre->pNext=p->pNext; // 这里明显有问题。
delete p;
cout<<"删除成功!"<<endl;
return;
}
p=p->pNext;
}


/****修改后***/
while(p->next!=NULL) //因为你是单链,删除后,找不到前驱节点。
{
pPre=p->next; //pPre标记要删除的对象
if(ID==p->next->sID)//唯一,所以查找到后直接删除,不用继续查找
{
p->pNext=p->pNext->next; //要删除pPre,p指向它
delete pPre;
cout<<"删除成功!"<<endl;
return;
}
p=p->pNext;
}

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧