温馨提示×

c语言创建链表的方法是什么

小亿
84
2024-03-18 21:12:40
栏目: 编程语言

在C语言中,创建链表通常需要定义一个结构体来表示链表的节点,然后通过动态内存分配来动态创建节点,并通过指针将节点连接起来形成链表。

以下是一个简单的示例代码,演示了如何使用C语言创建一个单向链表:

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

// 定义链表节点结构体
struct Node {
    int data;
    struct Node *next;
};

// 创建新节点
struct Node* createNode(int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 在链表末尾插入新节点
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;
}

上述代码定义了一个包含数据和指向下一个节点的指针的链表节点结构体Node,并实现了创建新节点、在链表末尾插入新节点和打印链表的函数。最后,在main函数中演示了如何创建一个包含数据1、2和3的链表,并打印出链表的内容。

0