C语言动态数据结构
2016-12-23 20:59
106 查看
静态链表
静态数据结构一般指 整型,浮点型 ,数组。它们固定大小动态数据结构指的是 动态存储分配
链表是一种常见的基础数据结构,是一种线性表,但是并不会按线性的顺序存储数据,而是在每一个节点里存到下一个节点的指针(Pointer)
静态链表:所有节点在程序中定义,而不是临时开辟
#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; //2 连成链表。 head = &a;//第一个节点地址赋给头指针head a.next = &b;// b.next = &c; c.next = NULL;// 链表最后一个元素 指针变量为空 struct weapon *p;//借助指针P访问节点 p = head;// 头指针 while(p!=NULL){ printf("%d,%d\n",p->atk,p->price); p= p->next;//指向下一个节点 } return 0; }
动态链表
#include <stdio.h> #include <malloc.h> // struct weapon { int price; int atk; //struct 结构体名 *变量名; struct weapon *next;//指针变量 存放下一个节点地址 }; // struct weapon *create(){ struct weapon *head;//头指针 struct weapon *p1,*p2;//p1 当前新创建节点,p2上一个节点 int n=0;//记录当前节点个数 //使用malloc函数(malloc分配内存块的函数,sizeof判断数据类型长度) p1 = p2 = (struct weapon *)malloc(sizeof(struct weapon));//使用malloc函数开辟第一个节点 scanf("%d,%d",&p1->price,&p1->atk);//第一个节点单独赋值 head = NULL;// //约定price为0,就不把节点放入列表(结束) 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->atk,p->price); return 0; }