c語(yǔ)言創(chuàng)建鏈表的方法是什么

小億
85
2024-03-18 21:12:40

在C語(yǔ)言中,創(chuàng)建鏈表通常需要定義一個(gè)結(jié)構(gòu)體來(lái)表示鏈表的節(jié)點(diǎn),然后通過(guò)動(dòng)態(tài)內(nèi)存分配來(lái)動(dòng)態(tài)創(chuàng)建節(jié)點(diǎn),并通過(guò)指針將節(jié)點(diǎn)連接起來(lái)形成鏈表。

以下是一個(gè)簡(jiǎn)單的示例代碼,演示了如何使用C語(yǔ)言創(chuàng)建一個(gè)單向鏈表:

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

// 定義鏈表節(jié)點(diǎn)結(jié)構(gòu)體
struct Node {
    int data;
    struct Node *next;
};

// 創(chuàng)建新節(jié)點(diǎn)
struct Node* createNode(int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 在鏈表末尾插入新節(jié)點(diǎn)
void insertNode(struct Node** head, int data) {
    struct Node* newNode = createNode(data);
    if (*head == NULL) {
        *head = newNode;
    } else {
        struct Node* current = *head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;
    }
}

// 打印鏈表
void printList(struct Node* head) {
    struct Node* current = head;
    while (current != NULL) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    printf("NULL\n");
}

int main() {
    struct Node* head = NULL;

    insertNode(&head, 1);
    insertNode(&head, 2);
    insertNode(&head, 3);

    printf("Linked list: ");
    printList(head);

    return 0;
}

上述代碼定義了一個(gè)包含數(shù)據(jù)和指向下一個(gè)節(jié)點(diǎn)的指針的鏈表節(jié)點(diǎn)結(jié)構(gòu)體Node,并實(shí)現(xiàn)了創(chuàng)建新節(jié)點(diǎn)、在鏈表末尾插入新節(jié)點(diǎn)和打印鏈表的函數(shù)。最后,在main函數(shù)中演示了如何創(chuàng)建一個(gè)包含數(shù)據(jù)1、2和3的鏈表,并打印出鏈表的內(nèi)容。

0