求助:关于链表中的双指针
本人正在研究链表,对于指针或是双重指针的区别用法不太明白下面有两个具体的例子,希望能得到某位好心高人的点拨~
******************使用单指针后运行错误的cpp文件内容**************************
#include <iostream.h>
struct NODE
{
int data;
NODE *next;
};
NODE *head=NULL;
int data[6]={25,41,17,98,5,67};
void InsertList(NODE *head,int aData,int bData);
void DeleteList(NODE *head,int aData);
void OutputList(NODE *head);
void InsertList(NODE *head,int aData,int bData)
{
NODE *p,*a,*b;
b=(NODE*)new(NODE);
b->data=bData;
p=head;
if(p==NULL)
{
head=b;
b->next=NULL;
}
else
if(p->data==aData)
{
b->next=p;
head=b;
}
else
{
while(p->data!=aData&&p->next!=NULL)
{
a=p;
p=p->next;
}
if(p->data==aData)
{
a->next=b;
b->next=p;
}
else
{
p->next=b;
b->next=NULL;
}
}
}
void OutputList(NODE *head)
{
NODE *p=head;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<"\n";
}
void DeleteList(NODE *head,int aData)
{
NODE *p,*a;
p=head;
if(p==NULL)
return;
if(p->data==aData)
{
head=p->next;
delete p;
}
else
{
while(p->data!=aData&&p->next!=NULL)
{
a=p;
p=p->next;
}
if(p->data==aData)
{
a->next=p->next;
delete p;
}
}
}
void main()
{
for(int i=0;i<6;i++)
InsertList(head,data[0],data[i]);
OutputList(head);
DeleteList(head,98);
DeleteList(head,41);
OutputList(head);
}
******************使用双重指针后运行正确的cpp文件内容**************************
#include <iostream.h>
struct NODE
{
int data;
NODE *next;
};
NODE *head=NULL;
int data[6]={25,41,17,98,5,67};
void InsertList(NODE **head,int aData,int bData);
void DeleteList(NODE **head,int aData);
void OutputList(NODE *head);
void InsertList(NODE **head,int aData,int bData)
{
NODE *p,*a,*b;
b=(NODE*)new(NODE);
b->data=bData;
p=*head;
if(p==NULL)
{
*head=b;
b->next=NULL;
}
else
if(p->data==aData)
{
b->next=p;
*head=b;
}
else
{
while(p->data!=aData&&p->next!=NULL)
{
a=p;
p=p->next;
}
if(p->data==aData)
{
a->next=b;
b->next=p;
}
else
{
p->next=b;
b->next=NULL;
}
}
}
void OutputList(NODE *head)
{
NODE *p=head;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<"\n";
}
void DeleteList(NODE **head,int aData)
{
NODE *p,*a;
p=*head;
if(p==NULL)
return;
if(p->data==aData)
{
*head=p->next;
delete p;
}
else
{
while(p->data!=aData&&p->next!=NULL)
{
a=p;
p=p->next;
}
if(p->data==aData)
{
a->next=p->next;
delete p;
}
}
}
void main()
{
for(int i=0;i<6;i++)
InsertList(&head,data[0],data[i]);
OutputList(head);
DeleteList(&head,98);
DeleteList(&head,41);
OutputList(head);
}
*****************************************************************
区别在于子函数中的head变量,前者用的是*head,后者则是**head,为什么第一种方法是不对的?
链表范例.rar
(227.23 KB)
/******附件为可编译通过的VC环境********/