您的位置:首页 > 理论基础 > 数据结构算法

动态数据结构——动态链表(malloc函数的使用)

2018-02-26 21:30 239 查看
#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),&(p2->atk));
head = NULL;
while(p1-> price != 0){
n++;
if(n == 1) head = p1;
else p2->next = p1;//p2为上一节点

p2 = p1;//更新
p1 = (struct weapon * )malloc(sizeof(struct weapon));
scanf("%d %d",&(p1->price),&(p1->atk));
}
p2->next = NULL;//此时p2为最后一个节点
return (head);
};

int main()
{
struct weapon * p;
p = create();
printf("%d,%d",p->price,p->atk);
return 0;
}

运行结果:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C