为什么head指针必须为引用指针型?Node*&head?.请各位帮忙调试一下.

北狐狸 2006-03-29 03:42:48
//================================================
// lihubei@yahoo.com.cn
//================================================
//
#include<iostream.h>
typedef struct node
{
int data;
struct node *link;
} Node;
//
//================================================
//
//为什么head指针必须为引用指针型?Node*&head?.
void reverseMySingleLink ( Node* head, Node *p, Node *q)
//void reverseMySingleLink ( Node* &head, Node *p, Node *q)
{
cout<<endl<<"反序将开始__*head.data: "<<head->data<<endl;
if(!head||!head->link)
{
cout<<"空链表或单结点"<<endl;
return;
}
//至少有两个结点.
p=head->link;
head->link=0;
q=p->link;

while(q)
{
p->link=head;
head=p;
p=q;
q=q->link;

}

p->link=head;
head=p;
cout<<"反序将退出__*head.data: "<<head->data<<endl;
}
//
//================================================
//
void main()
{
Node *head,*p,*q;
head=new Node;
p=new Node;
q=new Node;
//
head->link=p;
p->link=q;
q->link=0;
//
head->data=1;
p->data=2;
q->data=3;
cout<<"反序前__ *head.data: "<<head->data<<endl;

//start reverse this single linkList.
reverseMySingleLink(head,p,q);
//
cout<<endl<<"反序后__ *head.data: "<<head->data<<endl;
}
//
//================================================
...全文
114 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
北狐狸 2006-03-29
  • 打赏
  • 举报
回复
修正:
void putoutMyint(int *a,int *b,int *c)
{
cout<<"前 *f:__"<<*a<<","<<*b<<","<<*c<<endl;
int *temp=a;
a=b;
b=c;
c=temp;
cout<<"后 *f__"<<*a<<","<<*b<<","<<*c<<endl;
}
北狐狸 2006-03-29
  • 打赏
  • 举报
回复
那请ykzhujiang(朱朱)帮我调试一下这个:
引用<===>指针
值传递<===>非值传递

//
#include<iostream.h>

void putoutMyint(int a,int b,int c)
{
cout<<"前 f__"<<a<<","<<b<<","<<c<<endl;
int temp=a;
a=b;
b=c;
c=temp;
cout<<"后 f__"<<a<<","<<b<<","<<c<<endl;
}
void putoutMyint(int *a,int *b,int *c)
{
cout<<"前 *f:__"<<*a<<","<<*b<<","<<*c<<endl;
int temp=*a;
*a=*b;
*b=*c;
*c=temp;
cout<<"后 *f__"<<*a<<","<<*b<<","<<*c<<endl;
}
void putoutMyint3(int &a,int &b,int &c)
{
cout<<"前 &f__"<<endl;
int temp=a;
a=b;
b=c;
c=temp;
cout<<"后 &f__"<<a<<","<<b<<","<<c<<endl;
}

void main()
{
int a=1,
b=2,
c=3;
putoutMyint(a,b,c);
cout<<a<<","<<b<<","<<c<<endl;
a=1,
b=2,
c=3;
int *pa=&a,*pb=&b,*pc=&c;
putoutMyint(pa,pb,pc);
cout<<a<<","<<b<<","<<c<<endl;
a=1,
b=2,
c=3;
putoutMyint3(a,b,c);
cout<<a<<","<<b<<","<<c<<endl;

}
ykzhujiang 2006-03-29
  • 打赏
  • 举报
回复
因为函数参数是值传递,因此如果不用引用函数内部对指针指向的修改并不影响外部指针

64,635

社区成员

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

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