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

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

Node* create_list(int arr[], int size) {
    Node *head, *p, *q;
    head = (Node*)malloc(sizeof(Node));
    head->next = NULL;
    q = head;
    for (int i = 0; i < size; i++) {
        p = (Node*)malloc(sizeof(Node));
        p->data = arr[i];
        p->next = NULL;
        q->next = p;
        q = p;
    }
    return head;
}

void print_list(Node* head) {
    Node* p = head->next;
    printf('List: ');
    while (p != NULL) {
        printf('%d ', p->data);
        p = p->next;
    }
    printf('
');
}

int main() {
    int arr[] = {1, 2, 3};
    int size = sizeof(arr) / sizeof(int);
    Node* head = create_list(arr, size);
    print_list(head);
    return 0;
}

输出:

List: 1 2 3
C语言创建单链表并赋值:详细代码示例

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

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