我在学习链表的头插法,我写的代码在notepade++上面编译通过后,输入值后,无限打印,不知道是什么原因?有知道的兄弟吗
#include <stdio.h>
#include <stdlib.h>
struct Test {
int data;
struct Test *next;
};
void printLink(struct Test *head) {
struct Test *point = head;
while (point != NULL) {
printf("%d ", point->data);
point = point->next;
}
printf("\n");
}
struct Test* insertFromHead(struct Test *head) {
int newData;
struct Test *newNode;
while (1) {
printf("please input your new node data:\n");
if (scanf("%d", &newData) != 1) {
printf("Invalid input\n");
return head;
}
if (newData == 0) {
printf("0 quit!!\n");
return head;
}
newNode = (struct Test *)malloc(sizeof(struct Test));
if (newNode == NULL) {
printf("Memory allocation failed\n");
return head;
}
newNode->data = newData;
newNode->next = head;
head = newNode;
}
return head;
}
void freeList(struct Test *head) {
struct Test *current = head;
while (current != NULL) {
struct Test *temp = current;
current = current->next;
free(temp);
}
}
int main() {
struct Test *head = NULL;
head = insertFromHead(head);
printLink(head);
freeList(head);
return 0;
}
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/206566813007193.png "#left")