c语言如何创建一个链表

   2024-10-02 8790
核心提示:在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));    if (newNode == NULL) {        printf("Memory allocation failed");        exit(1);    }    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;        return;    }    struct Node* current = *head;    while (current->next != NULL) {        current = current->next;    }    current->next = newNode;}// 打印链表void printList(struct Node* head) {    while (head != NULL) {        printf("%d -> ", head->data);        head = head->next;    }    printf("NULL\n");}int main() {    struct Node* head = NULL;    insertNode(&head, 1);    insertNode(&head, 2);    insertNode(&head, 3);    printList(head);    return 0;}

在这个例子中,首先定义了一个表示链表节点的结构体Node,然后定义了一个createNode函数来创建一个新的节点,一个insertNode函数来插入新节点到链表的末尾,以及一个printList函数来打印链表。

在main函数中,首先创建一个空链表,然后插入三个节点,并最后打印出整个链表的内容。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号