动态数据结构:不用事先定义好固定的内存空间
静态链表
#include <stdio.h>
struct weapon{
int price;
int atk;
struct weapon * next;//用来存放下一个节点的地址
};
int main(){
struct weapon a ,b ,c, *head;
a.price=100;
a.atk=100;
b.price=200;
b.atk=200;
c.price=300;
c.atk=300;
head=&a;
a.next=&b;
b.next=&c;
c.next=NULL;
struct weapon *p;
p=head;
while(p!=NULL){
printf("%d,%d\n",p->atk,p->price);
p=p->next;
}
return 0;
}
动态链表
#include <stdio.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)); //malloc分配内存块的函数 sizeof判断数据类型的长度符
scanf("%d,%d",&p1->price,&p1->atk);//第一个节点单独做处理
head=NULL;//因为开始时链表不存在,所以赋给head一个初值
//
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();
printf("%d,%d",p->price,p->atk);
return 0;
}
静态链表
#include <stdio.h>
struct weapon{
int price;
int atk;
struct weapon * next;//用来存放下一个节点的地址
};
int main(){
struct weapon a ,b ,c, *head;
a.price=100;
a.atk=100;
b.price=200;
b.atk=200;
c.price=300;
c.atk=300;
head=&a;
a.next=&b;
b.next=&c;
c.next=NULL;
struct weapon *p;
p=head;
while(p!=NULL){
printf("%d,%d\n",p->atk,p->price);
p=p->next;
}
return 0;
}
动态链表
#include <stdio.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)); //malloc分配内存块的函数 sizeof判断数据类型的长度符
scanf("%d,%d",&p1->price,&p1->atk);//第一个节点单独做处理
head=NULL;//因为开始时链表不存在,所以赋给head一个初值
//
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();
printf("%d,%d",p->price,p->atk);
return 0;
}