作业帮 > 综合 > 作业

如head是头指针和头结点的区别

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/05/11 13:16:56
如head是头指针和头结点的区别
我理解的是head去指向头结点,如果符合作者的条件就不断申请动态内存,然后head就不停的替换新生成的结点,把head的地址拿给新结点,把新结点的地址拿给head是不是这样理解呢?急
#include
using namespace std;
class list
{
public:
\x05list *head;
\x05list *next;
\x05int data;
\x05void creat()
\x05{
\x05\x05int x;
\x05\x05cin>>x;
\x05\x05while(x!='#')
\x05\x05{
\x05\x05\x05list *s=new list;
\x05\x05\x05s->data=x;
\x05\x05\x05s->next=head->next;
\x05\x05\x05head->next=s;
\x05\x05\x05cin>>x;
\x05\x05}
\x05}
\x05
};
void main()
{
\x05list p;
\x05p.creat();
}这个代码哪里错了呢?
// 1. 你的程序在第一次s->next=head->next;会挂,因为head是指针,并非实体节点,且head没  //      有初始化很危险#include <iostream>using namespace std;class list{public:list *head;list *next;int data;list(){ head = NULL;                 next  =  NULL;}void creat(){int x;cin>>x;while(!cin.fail()) // x!='#' 判断,cin会类型检查,不会赋值给x的,所以将会是死循环{list *s=new list;s->data=x;s->next = NULL;s->next = head;head = s;cin.clear();  /* 错误位重置 */cin.sync();   /* 清空缓存区 */cin>>x;}}       // 增加打印显示void display(){list *pl;pl = head;while(pl){cout<<pl->data<<" ";pl = pl->next;}cout<<endl;}};void main(){list p;p.creat();p.display();}
再问: s->next = head; head = s; 这两句我真的还没能理解的,s->next=head我理解的是,你把head的地址赋给s->next,为什么又把s的地址赋给head呢?希望帮我解释下噶~~链表这里有些问题, 我认为,head就是个头指针,别个把地址拿给它,它去指向,这样理解对吗?
再答: head 只是一个指针,如图: