溫馨提示×

c語言createlist函數如何聲明

小億
231
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女