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

在C中如何在链表末尾添加元素?

在C语言中,可以通过以下步骤在链表末尾添加元素:

  1. 定义一个新的节点,用于存储要添加的元素。
  2. 检查链表是否为空,如果为空,则将新节点设置为链表的头节点。
  3. 如果链表不为空,遍历链表直到达到最后一个节点。
  4. 将最后一个节点的指针指向新节点。
  5. 将新节点的指针设置为NULL,表示链表的末尾。
  6. 添加完成后,更新链表的长度。

以下是一个示例代码:

代码语言:txt
复制
#include <stdio.h>
#include <stdlib.h>

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

// 在链表末尾添加元素
void append(struct Node** head_ref, int new_data) {
    // 创建新节点
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    struct Node* last = *head_ref;

    // 设置新节点的数据
    new_node->data = new_data;
    new_node->next = NULL;

    // 如果链表为空,则将新节点设置为头节点
    if (*head_ref == NULL) {
        *head_ref = new_node;
        return;
    }

    // 遍历链表直到达到最后一个节点
    while (last->next != NULL) {
        last = last->next;
    }

    // 将最后一个节点的指针指向新节点
    last->next = new_node;
}

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

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

    // 在链表末尾添加元素
    append(&head, 1);
    append(&head, 2);
    append(&head, 3);

    // 打印链表
    printf("链表内容:");
    printList(head);

    return 0;
}

这段代码演示了如何在链表末尾添加元素。首先定义了一个链表节点结构,包含数据和指向下一个节点的指针。然后通过append函数,在链表末尾添加新的节点。最后通过printList函数打印链表内容。

腾讯云相关产品和产品介绍链接地址:

  • 云服务器(CVM):https://cloud.tencent.com/product/cvm
  • 云数据库 MySQL 版(CMYSQL):https://cloud.tencent.com/product/cmysql
  • 人工智能平台(AI Lab):https://cloud.tencent.com/product/ailab
  • 腾讯云物联网平台(IoT Explorer):https://cloud.tencent.com/product/iothub
  • 腾讯云移动开发平台(MPS):https://cloud.tencent.com/product/mps
  • 对象存储(COS):https://cloud.tencent.com/product/cos
  • 腾讯云区块链服务(Tencent Blockchain):https://cloud.tencent.com/product/tencentblockchain
  • 腾讯云元宇宙(Tencent Metaverse):https://cloud.tencent.com/product/metaverse
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券