正确代码:
#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));
不添加的话就会一直在同一个地址创建节点,陷入死循环