c语言创建节点时如果不能提前确定节点的个数怎么创建?想到一种用CTRL + Z 想知道有没有什么方法能输完数字直接回车就行,不用Ctrlz。
while ((ch = getchar()) != '\n')
...
【以下回答由 GPT 生成】
要在C语言中创建一个可变大小的链表,可以使用动态内存分配函数malloc
和calloc
来分配内存来创建节点。以下是一个例子:
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
struct Node {
int data;
struct Node* next;
};
// 在链表末尾插入新的节点
void insert(struct Node** head, int data) {
// 创建新的节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
// 如果链表为空,则新节点为头节点
if (*head == NULL) {
*head = newNode;
}
// 否则,在链表尾部插入新节点
else {
struct Node* curr = *head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = newNode;
}
}
// 打印链表
void printList(struct Node* head) {
struct Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
int data;
// 循环读取用户输入的数字,直到输入非数字为止
while (scanf("%d", &data) == 1) {
insert(&head, data);
}
// 打印链表
printList(head);
return 0;
}
在这个例子中,我们使用insert
函数在链表的末尾插入新的节点,并使用printList
函数打印链表。在main
函数中,我们使用scanf
函数循环读取用户输入的数字,并将其插入到链表中,直到用户输入非数字为止。
这样,你就可以直接按回车键输入数字,而不需要使用Ctrl + Z来结束输入。
【相关推荐】