学习数据节构和算法的第14天

题目讲解

链表的移除

#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
    int data;              // 节点数据
    struct Node* next;     // 指向下一个节点的指针
} Node;
// 初始化链表节点
Node* initNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));    // 分配新节点的内存
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}
// 移除指定数值的节点
Node* removeElements(Node* head, int val) {
    Node* dummy = initNode(-1);    // 设置一个虚拟头节点,方便处理删除头节点的情况
    dummy->next = head;            // 将虚拟头节点指向原链表的头节点
    Node* current = dummy;         // 当前节点指针
    while (current->next) {
        if (current->next->data == val) {
            Node* temp = current->next;
            current->next = current->next->next;
            free(temp);             // 释放目标节点的内存
        } else {
            current = current->next;
        }
    }
    return dummy->next;             // 返回排除目标节点后的链表头节点
}
// 显示链表元素
void display(Node* head) {
    Node* current = head;
    while (current) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    printf("NULL\n");
}
int main() {
    // 创建链表: 1 -> 2 -> 3 -> 4 -> 5 -> NULL
    Node* head = initNode(1);
    head->next = initNode(2);
    head->next->next = initNode(3);
    head->next->next->next = initNode(4);
    head->next->next->next->next = initNode(5);
    printf("Original linked list: ");
    display(head);    // 显示原链表
    // 移除数值为3的节点
    head = removeElements(head, 3);
    printf("After removing elements: ");
    display(head);    // 显示移除元素后的链表
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值