以下是一个简单的删除链表元素的程序,其中包括了删除指定元素和销毁整个链表的功能。

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

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

// 删除指定元素
void deleteNode(Node** head_ref, int key){
    Node* temp = *head_ref, *prev;

    // 如果头节点是要删除的节点
    if (temp != NULL && temp->data == key){
        *head_ref = temp->next;
        free(temp);
        return;
    }

    // 找到要删除的节点
    while (temp != NULL && temp->data != key){
        prev = temp;
        temp = temp->next;
    }

    // 如果未找到要删除的节点
    if (temp == NULL){
        printf("Element not found\n");
        return;
    }

    // 从链表中删除节点
    prev->next = temp->next;
    free(temp);
}

// 销毁整个链表
void destroyList(Node** head_ref){
    Node* current = *head_ref, *next;

    while (current != NULL){
        next = current->next;
        free(current);
        current = next;
    }

    *head_ref = NULL;
}

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

// 测试删除链表元素的程序
int main(){
    Node* head = NULL;
    Node* second = NULL;
    Node* third = NULL;

    // 分配3个节点的内存
    head = (Node*) malloc(sizeof(Node));
    second = (Node*) malloc(sizeof(Node));
    third = (Node*) malloc(sizeof(Node));

    // 链接节点
    head->data = 1;
    head->next = second;

    second->data = 2;
    second->next = third;

    third->data = 3;
    third->next = NULL;

    printf("Original list: \n");
    printList(head);

    // 删除第二个节点
    deleteNode(&head, 2);
    printf("\nList after deleting node with key = 2: \n");
    printList(head);

    // 销毁整个链表
    destroyList(&head);
    printf("\nList after destroying: \n");
    printList(head);

    return 0;
}
``
c语言写一个删除链表元素的程序

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

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