温馨提示×

c语言createlist函数如何声明

小亿
125
2023-11-22 14:50:43
栏目: 编程语言

在C语言中,可以使用以下方式声明createlist函数:

struct ListNode {
    int val;
    struct ListNode *next;
};

struct ListNode* createlist(int arr[], int n) {
    struct ListNode *head = NULL;
    struct ListNode *curr = NULL;

    for (int i = 0; i < n; i++) {
        struct ListNode *newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
        newNode->val = arr[i];
        newNode->next = NULL;

        if (head == NULL) {
            head = newNode;
            curr = newNode;
        } else {
            curr->next = newNode;
            curr = curr->next;
        }
    }

    return head;
}

以上是一个示例的createlist函数声明,该函数用于根据给定的数组生成一个链表。函数首先定义了一个名为ListNode的结构体,其中包含一个整数val和一个指向下一个结点的指针next。接着声明了createlist函数,该函数的参数包括一个整数数组arr和数组长度n。函数内部首先创建一个头结点head和一个当前结点curr,并将它们初始化为NULL。然后使用循环遍历数组,创建新的结点并将其加入链表中。最后返回头结点head。

0