c语言使用头插法创建单链表陷入了死循环了怎么回事

正确代码:

#include<stdio.h>
#include<stdlib.h>
typedef struct SqList {
	char data;
	SqList* next;
}SqList;

void headInsert(SqList *H) {
	SqList* P = (SqList*)malloc(sizeof(SqList));
	char c=NULL;
	while (true) {
		P = (SqList*)malloc(sizeof(SqList));
		printf("请输入一个字符:");
		scanf_s("%c", &c);
		getchar();
		if (c == '#') {
			break;
		}
		P->data = c;
		//printf("%c", P->data);
		P->next = H->next;
		H->next = P;
	}
}

void print(SqList* H) {
	SqList* P=H;
	while (P != NULL) {
		printf("%c ", P->data);
		P = P->next;
	}
}

void tailInsert(SqList* T) {

}

int main() {
	SqList* H1 = (SqList*)malloc(sizeof(SqList));
	H1->next = NULL;
	headInsert(H1);
	print(H1->next);
	//printf("%c",H1->data);
}

错误代码:

#include<stdio.h>
#include<stdlib.h>
typedef struct SqList {
	char data;
	SqList* next;
}SqList;

void headInsert(SqList *H) {
	SqList* P = (SqList*)malloc(sizeof(SqList));
	char c=NULL;
	while (true) {
		printf("请输入一个字符:");
		scanf_s("%c", &c);
		getchar();
		if (c == '#') {
			break;
		}
		P->data = c;
		//printf("%c", P->data);
		P->next = H->next;
		H->next = P;
	}
}

void print(SqList* H) {
	SqList* P=H;
	while (P != NULL) {
		printf("%c ", P->data);
		P = P->next;
	}
}

void tailInsert(SqList* T) {

}

int main() {
	SqList* H1 = (SqList*)malloc(sizeof(SqList));
	H1->next = NULL;
	headInsert(H1);
	print(H1->next);
	//printf("%c",H1->data);
}

由此可见,陷入循环的原因在于,headInsert方法中的while循环中是否添加

P = (SqList*)malloc(sizeof(SqList));

不添加的话就会一直在同一个地址创建节点,陷入死循环

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值