C++初学者链表问题,请高手帮我注释下,每个语句!

struct node
{
int data;
node *next;
};
node *creatlist(int n);
int main(int argc, char *argv[])
{
int n;
node *listhead=null;
cout<<"jiedianshu"<<endl;
cin>>n;
if (n>0)
headlist=creatlist(n);
return 0;
}
node *creatlist(int n)
{
node *head=,*temp,*tail=null;
int num;
cin>>num;
head=new node;
if (head==null)
return null;
else
{
head->data=num;
head->next=null;
tail=head;
}
}
for (int i=0;i<n-1;i++)
{
cin>>num;
temp=new node;
if (temp==null)
return head;
else
{ temp->data=num;
temp->next=null;
tail->next=temp;
tail=temp;
}
}
return head;

以注释的形式解释了每行代码,希望可以帮助你;
struct node //链表的结构体,
{
int data;//data用于存放链表节点的数据
node *next;//next用于存储下一个链表节点,以此形成链表的链
};
node *creatlist(int n);//函数的前向生命,此函数功能是用于创建列表的

int main(int argc, char *argv[])
{
int n;//用于保存用户输入的节点个数
node *listhead = NULL;//定义了链表的头指针
cout<<"jiedianshu"<<endl;//打印输出“jiedianshu”字符串
cin>>n;//终端用户输入链表节点个数
if (n>0)//如果n大于零,则创建链表,否则直接返回。
listhead=creatlist(n);
return 0;
}

node *creatlist(int n)
{
node *head=NULL ,*temp = NULL ,*tail= NULL; //定义了三个空指针
int num;//链表头节点保存的数据;
cin>>num;
head = new node; //创建头节点
if (head == NULL) //如果new的为空,则字节返回空;
return NULL;
else
{
head->data=num;//把输入的num保存在链表头节点的data中;
head->next=NULL;//把头节点的下一个节点设置成为空,即初始化next指针为空;
tail=head;//把尾节点指向当前节点;
}
for (int i=0;i<n-1;i++)
{
cin>>num;//输入剩余节点要保存的数据
temp=new node;//创建剩余节点,用temp来临时保存
if (temp==NULL)
return head;//如果为空,则直接返回之前创建的head(这块除非内存不够了,一般不会new失败的)
else
{
temp->data=num;//把输入的数据保存在temp的data中;
temp->next=NULL;//把temp节点的下一个节点初始化为空;
tail->next=temp;//此时tail和head指向同一个节点,把其next指针指向temp这个心节点;
tail=temp;//然后再把tail指向temp节点,;
}
}
return head;//全部构造完毕后,返回头节点指针;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-01-15
高手!!!
相似回答