C语言中用struct创建链表,现在来看看过程是怎样的。
#include<stdio.h>
#include<stdlib.h>
typedef struct player
{
int account;
char name[20];
int HP;
int power;
int intelligence;
struct player *next;
}PLAYER;
PLAYER *Build(int num)
{
int i = 0;
PLAYER *Pt,*prePt,*head;
Pt = (PLAYER *)malloc(sizeof(PLAYER));
if(Pt != NULL)
{
scanf("%d%s%d%d%d",&Pt->account,Pt->name,&Pt->HP,&Pt->power,&Pt->intelligence);
head = Pt;
prePt = Pt;
}
else
{
printf("Failed.\n");
exit(0);
}
for(i = 1;i < num;i++)
{
Pt = (PLAYER *)malloc(sizeof(PLAYER));
if(Pt != NULL)
{
scanf("%d%s%d%d%d",&Pt->account,Pt->name,&Pt->HP,&Pt->power,&Pt->intelligence);
prePt->next = Pt;
prePt = Pt;
}
}
Pt->next = NULL;
return head;
}
int main()
{
PLAYER *head;
head = Build(3);
printf("The second player is:%d",head->account);
return 0;
}
这里的是一个可以创建任意节点的链表。我们知道C语言中,链表是用struct创建的。首先,定义一个结构体,用来存储数据和结构体指针,这个结构体指针就像是线一样将各个节点连接起来。我们将创建链表的过程放在函数中,那么首先要注意的就是要用malloc来申请空间,而不能直接在函数中定义变量,否则会出错。
在这里我们定义了三个指针,head是存放头节点的的指针,Pt用来存放新节点的指针,而prePt是存放当前链表尾节点的指针。头结点我们单独拿出来,因为头结点没有前驱节点。如果申请的空间正确,那么我们把节点的地址返回给Pt。而prePt总是用来保存当前链表尾节点的地址,只有一个头节点,因此将Pt的值赋给prePt。接下来就是除了头结点的其他节点的创建,步骤差不多。关键之处在于prePt->next存放的是新节点的地址,因此将新节点Pt的地址赋值给prePt->next,然后将prePt的值更新成Pt,因为Pt在变化,因此prePt也要跟上。创建完成之后,别忘了最后一个节点的next要指向NULL。