Linux C语言:动态数据结构

5-1 Linux C 动态数据结构–静态链表

在这里插入图片描述
链表里的各个地址不一定是连续的;

静态链表的定义、初始化以及遍历:

#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 = 150;
	b.price = 200;
	b.atk = 250;
	c.price = 300;
	c.atk =350;
	head = &a;
	a.next = &b;
	b.next = &c;
	c.next = NULL;

	struct weapon *p;
	p = head;
	while(p != NULL){
		printf("%d,%d\n",p->price,p->atk);
		p=p->next;
	}
	return 0;
}

输出结果:

linux@ubuntu:~/workspace2/les4$ ./a.out
100,150
200,250
300,350

静态链表的所有节点都是在程序中定义的,而不是临时开辟的;


5-2 Linux C 动态数据结构–动态链表

在程序执行的过程中,从无到有的建立起一个链表;

动态链表的定义、初始化以及访问:

linux@ubuntu:~/workspace2/les4$ cat link2.c
#include <stdio.h>
#include <malloc.h>

struct weapon{
	int price;
	int atk;
	struct weapon *next;
};

struct weapon *creat(){
	struct weapon *head;//head是链表的头指针
	struct weapon *p1 , *p2;//p1指向链表当前新创建的节点,p2指向上一个节点
	int n = 0; //n表示当前链表的节点个数
	p1=p2=(struct weapon*)malloc(sizeof(struct weapon));//malloc分配内存块的函数
	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=creat();
	printf("%d,%d\n",p->price,p->atk);
	return 0;
}

运行结果:

linux@ubuntu:~/workspace2/les4$ ./a.out
101,399
123,4324 
123,432
0,123
101,399
发布了30 篇原创文章 · 获赞 36 · 访问量 682

猜你喜欢

转载自blog.csdn.net/qq_42745340/article/details/104132514