利用两个指针实现单链表的结点的创建与录入
对于一个结点结构体:
struct student
{ long num ;
float score;
struct student *next;
};
我们定义两个结点:p1,p2;
struct student *p1,*p2;d
完全创建结点:
p1=p2=(struct student*)malloc(LEN);//#define LEN sizeof(struct student)
从主函数引入头头节点head,并且对p1赋值
scanf("%ld,%f",&p1->num ,&p1->score);
printf("%5ld,%15f\n",p1->num,p1->score);
建立循环while
循环包括计数器n,结点p1,p2,头结点head。
当n1时,把p1赋给head的后继元素,当n>1时,把p1赋值给p2的后继元素,并且令p2p1,然后对于p1进行赋值。
while(p1->num!=0){
n=n+1;
if(n==1) head->next=p1;
else p2->next=p1;
p2=p1;//p2就相当于一个temp
scanf("%ld,%f",&p1->num,&p1->score);
printf("%5ld,%15f\n",p1->num,p1->score);
}
最后要释放p2.
p2->next=NULL;
该方法可以对单链表进行按需实时扩充,节约内存。
完全代码如下:
struct student*creat(struct student*head){
struct student *p1,*p2;
int n=0;
printf("\n请按照学生学号顺序输入学生信息(学号和成绩)\n");
/*建立两个结点*/
p1=p2=(struct student*)malloc(LEN);
/*输入头节点*/
scanf("%ld,%f",&p1->num ,&p1->score);
printf("%5ld,%15f\n",p1->num,p1->score);
/*按需构建后续节点并输入信息*/
while(p1->num!=0){
n=n+1;
if(n==1) head->next=p1;
else p2->next=p1;
p2=p1;
scanf("%ld,%f",&p1->num,&p1->score);
printf("%5ld,%15f\n",p1->num,p1->score);
}
printf("\n一共增加%d位学生\n",n);
p2->next=NULL;
return head;
}
单链表的创建方法有很多种,可以根据实际项目情况来具体选择
待更新/