#include <stdio.h> #include <stdlib.h>

typedef struct Node { int data; struct Node* next; } Node;

Node* createNode(int data) { Node* newNode = (Node*)malloc(sizeof(Node)); if (newNode == NULL) { printf("Memory allocation failed."); exit(1); } newNode->data = data; newNode->next = NULL; return newNode; }

void addNode(Node** head, int data) { Node* newNode = createNode(data); if (*head == NULL) { head = newNode; } else { Node curr = *head; while (curr->next != NULL) { curr = curr->next; } curr->next = newNode; } }

void printList(Node* head) { Node* curr = head; while (curr != NULL) { printf("%d ", curr->data); curr = curr->next; } printf("\n"); }

void freeList(Node* head) { Node* curr = head; while (curr != NULL) { Node* temp = curr; curr = curr->next; free(temp); } }

int main() { int n; while (1) { scanf("%d", &n); if (n == 0) { break; }

    Node* head = NULL;
    for (int i = 0; i < n; i++) {
        int data;
        scanf("%d", &data);
        addNode(&head, data);
    }
    
    printList(head);
    freeList(head);
}

return 0;

}

上述代码实现了读取多组数据,每组数据中第一行为链表 A 的长度 n,第二行为链表 A 的 n 个元素。当 n=0 时输入结束。每组数据读取后,会创建链表 A 并打印出来,然后释放链表的内存。

C语言实现链表创建与打印:多组数据输入

原文地址: https://www.cveoy.top/t/topic/SDL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录