创建链表节点个数问题

c语言创建节点时如果不能提前确定节点的个数怎么创建?想到一种用CTRL + Z 想知道有没有什么方法能输完数字直接回车就行,不用Ctrlz。

while ((ch = getchar()) != '\n')
...

【以下回答由 GPT 生成】

要在C语言中创建一个可变大小的链表,可以使用动态内存分配函数malloccalloc来分配内存来创建节点。以下是一个例子:

#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来结束输入。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^