动态链表:所谓动态链表就是在程序执行过程中,从无到有的建立起一个链表。也就是说我们需要一个一个的去开辟新节点,并且输入各个节点的数据。然后建立起前后相连的关系。
#include<stdio.h>
#include<malloc.h>
struct weapon{ //公用体(也叫联合体)作用:让几个不同各类型的变量共享一块内存地址。
int price;
int atk;
struct weapon * next;
};
struct weapon * create(){
struct weapon * head;
struct weapon * p1,*p2;
int n=0;
p1=p2=(struct weapon*)malloc(sizeof(struct weapon));
scanf("%d,%d",&p1->price,&p1->atk);
head=NULL;
while(p1->price!=0){
n++;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=(struct weapon*)malloc(sizeof(struct weapon));
scanf("%d,%d",&p1->price,&p1->atk);
}
p2->next=NULL;
return(head);
}
int main()
{
struct weapon *p; //首先创建一个结构体指针
p=create(); //调用create函数。当前的p就是链表的头指针了
printf("%d,%d",p->price,p->atk);
return 0;
}
运行演示;