新微赢技术网
标题:
链表问题 , 首地址的值不能删除,为什么?
[打印本页]
作者:
无民
时间:
2009-11-3 00:53
标题:
链表问题 , 首地址的值不能删除,为什么?
#include<iostream>
using namespace std;
struct Person
{
char name[20];
int id;
Person* pN;
};
Person* head;
Person* creat()
{
Person* ps;
Person* pEnd;
ps = new Person;
cout<<"please enter the name :"<<endl;
cin>>ps->name;
cout<<"please enter the id :"<<endl;
cin>>ps->id;
pEnd = ps;
head = NULL;
while(ps->id != 0)
{
if(head == NULL)
{
head = ps;
}
else
{
pEnd->pN = ps;
}
pEnd = ps;
ps = new Person;
cout<<"please enter the name :"<<endl;
cin>>ps->name;
cout<<"please enter the id :"<<endl;
cin>>ps->id;
}
pEnd-> pN= NULL;
delete ps;
return (head);
}
void display(Person* head)
{
cout<<"Show this List :"<<endl;
while(head)
{
cout<<"Name is :"<<head->name<<endl;
cout<<"ID is :"<<head->id<<endl;
cout<<"********************************"<<endl;
head = head->pN;
}
}
void del(Person* head,int number)
{
Person* p;
if(!head)
{
cout<<"Empty of head"<<endl;
return ;
}
if(head->id == number)
{
p = head;
head = head->pN;
delete p;
cout<<"The head has delete the number"<<endl;
return ;
}
for(Person* pd = head;pd->pN;pd = pd->pN)
{
if(pd->pN->id == number)
{
p = pd->pN;
pd->pN = p->pN;
delete p;
cout<<"delete the number"<<endl;
return ;
}
}
}
int main()
{
head = creat();
del(head,54);
display(head);
system("pause");
return 0;
}
作者:
▄愛變鎖ゞ
时间:
2009-11-3 00:53
先抱怨一下,这个问题我好像以前解决过。不会是哪本书上的习题吧?
作者:
孤单一个人
时间:
2009-11-3 00:53
void del(Person* head,int number)
修正为void del(Person*& head,int number)
作者:
妊嫒ぞ流逝
时间:
2009-11-3 00:53
为啥要用引用指针呢,有点不明白了...
作者:
让爱留在心底
时间:
2009-11-3 00:53
通过打印函数内和函数外的head地址,你会发现函数内的head与函数外的head不一样。有点象值传递和引用传递。
这里你也可以利用head的全局变量的特点,把del和display的head参数去掉。运行也能成功。
作者:
叛逆ぁ太上皇
时间:
2009-11-3 00:53
解决啦,QQQ
欢迎光临 新微赢技术网 (http://bbs.weiying.cn/)
Powered by Discuz! X3.2