使用C语言实现循环单链表的基本操作

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

// 循环单链表节点结构
struct Node {
    int data;
    struct Node* next;  // 后继节点指针
};

// 在循环单链表的尾部插入一个元素
void insertAtTail(struct Node** head, int data) {
    // 创建新节点
    struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
    if (newNode == NULL) {
        printf("内存分配失败");
        return;
    }
    newNode->data = data;
    newNode->next = NULL;

    // 若链表为空,插入新节点并构成循环
    if (*head == NULL) {
        *head = newNode;
        newNode->next = *head;
        return;
    }

    // 找到链表尾部节点
    struct Node* tail = *head;
    while (tail->next != *head) {
        tail = tail->next;
    }

    // 链接新节点
    tail->next = newNode;
    newNode->next = *head;
}

// 在循环单链表中删除一个指定元素
void deleteNode(struct Node** head, int data) {
    // 若链表为空则直接返回
    if (*head == NULL) {
        printf("链表为空");
        return;
    }

    // 若删除的是头节点
    if ((*head)->data == data) {
        struct Node* curr = *head;
        struct Node* tail = *head;

        // 找到链表尾部节点
        while (tail->next != *head) {
            tail = tail->next;
        }

        // 移动头指针并删除头节点
        *head = (*head)->next;
        tail->next = *head;
        free(curr);
        return;
    }

    // 找到要删除的节点及其前驱节点
    struct Node* prev = *head;
    struct Node* curr = (*head)->next;
    while (curr != *head && curr->data != data) {
        prev = curr;
        curr = curr->next;
    }

    // 若未找到则直接返回
    if (curr == *head) {
        printf("未找到指定节点");
        return;
    }

    // 删除中间或尾部节点
    prev->next = curr->next;
    free(curr);
}

// 打印循环单链表所有元素
void printList(struct Node* head) {
    // 若链表为空则直接返回
    if (head == NULL) {
        printf("链表为空");
        return;
    }

    struct Node* curr = head;
    do {
        printf("%d ", curr->data);
        curr = curr->next;
    } while (curr != head);
    printf("\n");
}

// 主函数
int main() {
    struct Node* head = NULL;

    // 在循环单链表尾部插入元素
    insertAtTail(&head, 5);
    insertAtTail(&head, 10);
    insertAtTail(&head, 15);
    printf("循环单链表插入之后的结果: ");
    printList(head);

    // 删除循环单链表中的元素
    deleteNode(&head, 10);
    printf("删除元素10后的结果: ");
    printList(head);

    return 0;
}

 

posted @ 2023-07-03 23:04  nullIsland01  阅读(75)  评论(0)    收藏  举报