以下是使用C语言实现单向循环链表的例子:

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

// 定义链表节点
typedef struct Node {
    int data;           // 数据域
    struct Node* next;  // 指针域
} Node;

// 初始化链表
Node* initList() {
    Node* head = (Node*)malloc(sizeof(Node));  // 创建头节点
    head->next = head;  // 头节点的下一个指针指向自己,形成循环链表
    return head;
}

// 在链表尾部插入节点
void insert(Node* head, int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));  // 创建新节点
    newNode->data = data;
    newNode->next = head;  // 新节点的next指针指向头节点

    Node* temp = head;
    while (temp->next != head) {
        temp = temp->next;
    }
    temp->next = newNode;  // 将新节点插入到尾部
}

// 删除链表中的指定节点
void delete(Node* head, int data) {
    Node* temp = head->next;
    Node* prev = head;
    while (temp != head) {
        if (temp->data == data) {
            prev->next = temp->next;  // 删除节点
            free(temp);  // 释放节点内存
            return;
        }
        prev = temp;
        temp = temp->next;
    }
}

// 修改链表中指定节点的值
void modify(Node* head, int oldData, int newData) {
    Node* temp = head->next;
    while (temp != head) {
        if (temp->data == oldData) {
            temp->data = newData;  // 修改节点值
            return;
        }
        temp = temp->next;
    }
}

// 在链表中查找指定节点
Node* search(Node* head, int data) {
    Node* temp = head->next;
    while (temp != head) {
        if (temp->data == data) {
            return temp;
        }
        temp = temp->next;
    }
    return NULL;
}

// 打印链表
void display(Node* head) {
    Node* temp = head->next;
    while (temp != head) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

// 释放链表内存
void freeList(Node* head) {
    Node* temp = head->next;
    while (temp != head) {
        Node* next = temp->next;
        free(temp);
        temp = next;
    }
    free(head);
}

int main() {
    Node* head = initList();  // 初始化链表

    // 插入节点
    insert(head, 1);
    insert(head, 2);
    insert(head, 3);
    insert(head, 4);
    insert(head, 5);

    printf("初始链表:");
    display(head);

    // 删除节点
    delete(head, 3);
    printf("删除节点后:");
    display(head);

    // 修改节点
    modify(head, 2, 6);
    printf("修改节点后:");
    display(head);

    // 查找节点
    Node* result = search(head, 6);
    if (result != NULL) {
        printf("查找到节点:%d\n", result->data);
    } else {
        printf("未找到节点\n");
    }

    // 释放链表内存
    freeList(head);

    return 0;
}

输出结果:

初始链表:1 2 3 4 5 
删除节点后:1 2 4 5 
修改节点后:1 6 4 5 
查找到节点:6
``
用C语言写单向循环链表实现增删改查

原文地址: https://www.cveoy.top/t/topic/iqKE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录