关于双向循环链表删除时遇到的问题?

aleyn 2010-03-31 10:47:11
#include<iostream.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
typedef struct Student
{
char *num;
char *name;
double math,computer,chinese,sum;
struct Student *prior,*next;
}Stu;
int GetLength(Stu*L) //求长度
{
int i=0;
Stu *p=L->next;
while(p!=L)
{
p=p->next;i++;
}
return i;
}

void CreateList(Stu *&L) //建立双向循环链表
{
L=new Stu[sizeof(Stu)];
L->prior=L->next=L;
Stu *p,*q=L;
while(1)
{
p=new Stu[sizeof(Stu)];
p->prior=p->next=NULL;
p->num=new char[10];
cout<<"请输入学生的学号(当输入学号为“0000”时结束):";
cin>>p->num;
if(strcmp(p->num,"0000")==0)
return;
p->name=new char[10];
cout<<"请输入学生的姓名:";
cin>>p->name;
cout<<endl;
cout<<"请输入该学生的3科成绩(按math,computer,chinese的顺序输入):";
cin>>p->math;
cin>>p->computer;
cin>>p->chinese;
p->sum=p->math+p->computer+p->chinese;
q->next=p;
p->next=L;
p->prior=q;
L->prior=p;
q=p;
}
}
void PrintList(Stu *L) //输出成绩信息,和学生完整信息
{
Stu *p=L->next;
cout<<"********************输出学生的成绩信息***************************"<<endl;
while (p!=L)
{
cout<<"学号:"<<p->num<<" "<<"姓名:"<<p->name<<endl;
cout<<"math:"<<p->math<<" "<<"computer:"<<p->computer<<" ";
cout<<"chinese:"<<p->chinese<<" "<<"sum:"<<p->sum<<endl;
p=p->next;
}
cout<<endl;
}


void DeleteList(Stu*&L) //删除学生信息:给出学生姓名,删除链表所有相同姓名的学生的信息(即姓名相同的结点);
{int j=1;
char*s;
s=new char[10];
cout<<"请输入要删除学生的姓名:";
cin>>s;
cout<<GetLength(L)<<endl;
Stu *p=L,*q;
while(j<=GetLength(L))
{
p=p->next;

if(strcmp(p->name,s)==0)
{
p=p->prior;
q=p->next;
p->next=q->next;
q->next->prior=p;
delete[] q;
}
j++;
}
}
void main()
{
Stu *L;
CreateList(L);
PrintList(L);
DeleteList(L);
PrintList(L);
}

我想问的是,当这个链表中要删除存在相同姓名的结点时,当有一个结点是最后一个结点时,为什么不能删除姓名相同的最后一个结点?


...全文
67 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
aleyn 2010-04-13
  • 打赏
  • 举报
回复
void DeleteList(Stu*&L) //删除学生信息:给出学生姓名,删除链表所有相同姓名的学生的信息(即姓名相同的结点);
{int j=1;
char*s;
s=new char[10];
cout<<"请输入要删除学生的姓名:";
cin>>s;
cout<<GetLength(L)<<endl;
Stu *p=L,*q;
while(j<=GetLength(L))
{
p=p->next;

if(strcmp(p->name,s)==0)
{
p=p->prior;
q=p->next;
p->next=q->next;
q->next->prior=p;
delete[] q;
}
else //自个儿想明白了,这个地方少了个else;
j++;
}
}
JAVA_H 2010-04-01
  • 打赏
  • 举报
回复
这个嘛,就自个儿用C++来验证,就是了……
aleyn 2010-03-31
  • 打赏
  • 举报
回复
我觉得问题主要是在于删除函数上,但是我实在不晓得该怎么改了,望哪位高手指点下,当存在姓名相同的结点,其中有一个是最后一个结点时,删除函数不能删除相同姓名的最后一个结点,我想知道这是怎么回事,

33,007

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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