链表是很多人学习c语言的一个难点,本人刚好学到这一点,花了一些时间弄懂之后,想把它分享出来,以造福后来人。
由于水平实在有限,知识体系也不完全,如果有错误,请联系我,我会尽快改正。
*****************************************************************************************************************
链表是一种能够动态存储数据的一种数据结构。它能够跳跃式存储数据,可以方便数据的操作。
1.定义链表节点
struct note{
char name[20];
int heartlevel;
struct note *next;
};
我们定义一个名为note的结构。结构内有我们想要存储的数据类型与一个结构指针。这个指针是对链表操作的关键。这里,我想要存储数据生物名称【name】与生物血量【heartlevel】两种数据。2.头指针
根据我的理解,对一个链表操作的入口就是链表的头指针。对头指针的操作我们就可以对整个链表操作。我们在主函数内定义剪标的头指针head,并把它赋值为空值。
struct note *head;
head=NULL;
struct note *create(struct note *head){
struct note *p1=NULL,*p2=NULL;
char name[20];
int n;
while(scanf("%s",name)!=EOF){
p1=(struct note*)malloc(sizeof(struct note));
strcpy(p1->name,name);
scanf("%d",&n);
p1->heartlevel=n;
p1->next=NULL;
if(head==NULL)
head=p1;
else
p2->next=p1;
p2=p1;
}
return head;
}
char name[20];
int n;
void print(struct note *head){
struct note *temp;
temp=head;
while(temp!=NULL){
printf("name=%s ,heartlevel=%d\n",temp->name,temp->heartlevel);
temp=temp->next;
}
}
为了改变头指针,我们创建一个临时指针temp来操作#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct note{
char name[20];
int heartlevel;
struct note *next;
};
struct note *create(struct note *head){
struct note *p1=NULL,*p2=NULL;
char name[20];
int n;
while(scanf("%s",name)!=EOF){
p1=(struct note*)malloc(sizeof(struct note));
strcpy(p1->name,name);
scanf("%d",&n);
p1->heartlevel=n;
p1->next=NULL;
if(head==NULL)
head=p1;
else
p2->next=p1;
p2=p1;
}
return head;
}
void print(struct note *head){
struct note *temp;
temp=head;
while(temp!=NULL){
printf("name=%s ,heartlevel=%d\n",temp->name,temp->heartlevel);
temp=temp->next;
}
}
int main(int argc, const char * argv[]) {
struct note *head;
head=NULL;
head=create(head);
print(head);
return 0;
}