建立动态链表,结构体变量很适合链表,建立一个结构体变量,其中包括:期望输入的若干个数据,指向下一个链表元素的指针。
我们需要三个结构体指针(p1,p2,head),先申请一个动态存储空间,存放输入的数据。确定此为第一个数据并使head与p2指向此元素。再建立一个动态存储空间接收第二组数据,判断此数据为第二组数据后,使p2的指向下一元素的指针指向此元素(执行此操作前head、p2都是指向第一组数据,所以此操作就是令第一组数据指向下一元素的指针指向第二个元素)。再使p2指向第二组数据。再循环操作,就可以建立动态链表。(注意循环结束条件)
建立与输出链表
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct Stu)
//定义输入数据样式
struct Stu
{
long num;
float score;
struct Stu *next;
};
int n;
//建立链表
struct Stu *creat()
{
struct Stu *head,*p1,*p2;
n=0;
//接受第一组数据
p1=p2=(struct Stu*)malloc(LEN);
scanf("%ld,%f",&p1->num,&p1->score);
head=NULL;
//循环输入数据
while(p1->num!=0)
{
//判断是否使第一个数据
n+=1;
//使head指向第一组数据
if(n==1)head=p1;
//使第一组数据指向下一组数据地址
else p2->next=p1;
p2=p1;
//重新获取一组数据
p1=(struct Stu*)malloc(LEN);
scanf("%ld,%f",&p1->num,&p1->score);
}
//最后一组数据指向NULL
p2->next=NULL;
return(head);
}
//输出链表
void print(struct Stu*head)
{
struct Stu *p;
printf("\nNOW,These %d records are :\n",n);
p=head;
//判断是否有数据
if(head!=NULL)
do
{
printf("%ld %5.2f\n",p->num,p->score);
p=p->next;
}while(p!=NULL);
}
int main()
{
struct Stu *head;
printf("以(1,2)格式输入(0,0结束):\n");
head=creat();
print(head);
}