1.在建立动态链表之前,我们得先了解单链表的结构。用结构体(student)建立,并且分为数据域和指针域(student)。
2.在主函数中为头结点head开创一个大小为student的空间。并且将头结点head赋给临时头结点pre。
3.用一个for循环创建一个长度为n的链表。
4.在for循环中:先为普通结点p开创空间,然后为p的数据域赋值,再将p的地址存在pre的指针域中(per->next=p),而后将p赋予pre让当前节点成为临时头结点(pre=p),最后将p的指针域置空(p->next=NULL)作为遍历时的结束条件。
student* s(int n) //创建长度为N的链表
{
int i;
student *head=new student; //创建头结点
student *pre=head;
for(i=0;i<n;i++) //创建普通结点
{
student *p=new student;
cout<<"请输入第"<<i+1<<"个数据"; //输入数据
cin>>p->name>>p->fen;
pre->next =p; //创建结点间关系
pre=p;
p->next =NULL; //终点的标志(用于遍历时判断)
}
return head->next ; // head 内没有数据
}