链表的基本用法

普通链表

struct STR{
	int a;
	char c;
	struct STR *next;
};

struct STR *creat(){
	struct STR* head = NULL, * p1, * p2, * rear = NULL;
	int n = 0;
	p1 = p2 = (struct STR*)malloc(sizeof(struct STR));/*完全可以理解为p1的功能是不断创造新的变量
															 p2的功能是负责粘合原来的p1和新产生的p1的工具,类似于胶水和积木的关系*/
	while(~scanf("%d %c",p1->a,p1->c) ){
		n++;
		if (n == 1)
			head = p1;
		else
			p2->next = p1;/* p2->p=p1 和 p2=p1 容易写反,注意思考指针移动的先后顺序 */
		p2 = p1;
		p1 = (struct STR*)malloc(sizeof(struct STR));//编的时候漏了为p1开辟新的空间,超级超级容易漏  !!!!你个麻瓜注意点!!!!
	}
	p2->next = NULL;		//超级容易漏掉 要时刻警惕
	if (n != 0)
		rear = p2;
	return head;
}

head为链表必须有的变量, p1和p2是创建链表过程中的变量也是必须有的变量

rear变量不是必须有的根据链表的要求可以忽略

n的最主要作用就是判断当间节点是不是头结点,并将头结点给头指针,他还可以用于记录一共有多少节点

也是必须要有的

 

一般链表的模板

struct STR {
	...
        ...
	
			*各种变量*
	
	* 节点 *
	struct STR* next;
};

struct STR* creat() {
	struct STR* head = NULL, * p1, * p2, * rear = NULL;
	int n = 0;
	p1 = p2 = (struct STR*)malloc(sizeof(struct STR));

	while (输入一个数判断是否继续创造节点) {
		[剩余操作]
                ...
                ...
                ...

		n++;
		if (n == 1)
		    head = p1;
		else
		    p2->next = p1;
		p2 = p1;
		p1 = (struct STR*)malloc(sizeof(struct STR));
		
	}
	p2->next = NULL;		
	if (n != 0)
		rear = p2;
	return head;
}

文本

如果要将链表写入文本的话,直接使用链表是不能直接写入进去的

错误写法

struct STR {
    int a;
    char c;
    struct STR* next;
};

void write(STR*head) {
	FILE* fp;
	if ((fp = fopen("str.txt", "w")) == NULL) {
		printf("打开文件失败");
	}
	STR* p = head;
	for (;p != NULL;p = p->next)
		fwrite(p, sizeof(STR), 1, fp);
	printf("写入文件成功!\n");
	fclose(fp);
}

这里写的是错误的,因为这样写会把结构体中的next一同写入文本

但是在读取文本时读取的地址是无效地址

正确写法

struct STR {
    int a;
    char c;
};
struct str {
	STR* I;
	str* next;
};

void write(str*head) {
	FILE* fp;
	if ((fp = fopen("str.txt", "w")) == NULL) {
		printf("打开文件失败");
	}
	str* p = head;
	for (;p != NULL;p = p->next)
		fwrite(p->I, sizeof(STR), 1, fp);
	printf("写入文件成功!\n");
	fclose(fp);
}

可以仔细对照区别,在此是没有把地址写入文本的.真正是链表的是str结构体.STR结构体就相当于一个变量

所以从文本获取链表信息也就容易写

根据模板简单替换一下就行了

struct STR {
    int a;
    char c;
};
struct str {
	STR* I;
	str* next;
};
str* read() {
	FILE* fp;
	str* create, * head = NULL, * rear = NULL;
	int n = 0;
	if ((fp = fopen("car.txt", "r")) == NULL) {
		printf("打开文件失败");
		exit(0);
	}
	create = rear = (str*)malloc(sizeof(str));
	create->I = (STR*)malloc(sizeof(STR));
	while ((fread(create->I, sizeof(STR), 1, fp)) != 0) {
		n++;
		if (n == 1)
			head = rear;
		else
			rear->next = create;
		rear = create;
		create = (str*)malloc(sizeof(str));
		create->I = (STR*)malloc(sizeof(STR));
	}
	if (n != 0)
		rear->next = NULL;
	free(create->I);
	free(create);
	fclose(fp);
	printf("录入成功");
	return head;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值