首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

用C语言实现链表中的节点

链表是一种常见的数据结构,用于存储和组织数据。每个节点包含一个数据元素和一个指向下一个节点的指针。

C语言是一种广泛使用的编程语言,适用于系统级编程和嵌入式开发。下面是用C语言实现链表中的节点的示例代码:

代码语言:txt
复制
#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("内存分配失败\n");
        exit(1);
    }
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 在链表末尾插入节点
void insertAtEnd(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("\n");
}

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

    // 在链表末尾插入节点
    insertAtEnd(&head, 1);
    insertAtEnd(&head, 2);
    insertAtEnd(&head, 3);

    // 打印链表
    printList(head);

    return 0;
}

这段代码实现了一个简单的链表,包括创建节点、在链表末尾插入节点和打印链表的功能。通过调用insertAtEnd函数,可以向链表中插入新的节点。最后,调用printList函数可以打印链表中的所有节点。

链表的优势在于可以动态地分配内存,灵活地插入和删除节点。它适用于需要频繁插入和删除元素的场景,例如实现队列、栈、图等数据结构。

腾讯云提供了多种云计算相关产品,例如云服务器、云数据库、云存储等。具体的产品介绍和链接地址可以在腾讯云官方网站上查找。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券