【C语言练习】028. 理解链表的构建和遍历

028. 理解链表的构建和遍历

  • 028. 理解链表的构建和遍历
    • 1. 定义链表节点
      • 示例1:定义链表节点
    • 2. 构建链表
      • 示例2:构建链表
    • 3. 遍历链表
      • 示例3:遍历链表
        • 输出结果
    • 4. 释放链表内存
      • 示例4:释放链表内存
        • 输出结果
    • 5. 链表的插入操作
      • 示例5:在链表头部插入节点
        • 输出结果
    • 6. 链表的删除操作
      • 示例6:删除链表头部节点
        • 输出结果

028. 理解链表的构建和遍历

链表是一种常见的数据结构,由一系列节点组成,每个节点包含数据部分和指向下一个节点的指针。链表的构建和遍历是C语言编程中的重要技能。以下将详细介绍如何在C语言中构建和遍历链表。

1. 定义链表节点

链表的每个节点通常包含两个部分:数据和指向下一个节点的指针。在C语言中,可以使用结构体来定义链表节点。

示例1:定义链表节点

#include 
#include 

// 定义链表节点结构体
struct Node {
   
    int data;        // 数据部分
    struct Node *next; // 指向下一个节点的指针
};

2. 构建链表

构建链表通常涉及动态内存分配,使用malloc为每个节点分配内存,并将节点连接起来。

示例2:构建链表

#include 
#include 

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\n");
        exit(1);
    }
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

int main() {
   
    // 创建链表
    struct Node *head = createNode(1);
    head->next = createNode(2);
    head->next->next = createNode(3);

    return 0;
}

3. 遍历链表

遍历链表是指从链表的头节点开始,逐个访问每个节点,直到链表的末尾(即next指针为NULL)。

示例3:遍历链表

#include 
#include 

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\n");
        exit(1);
    

你可能感兴趣的:(从零开始学习机器人,c语言,链表,开发语言,算法,机器人,人工智能)