温馨提示×

c语言静态链表的删除操作

小樊
81
2024-09-08 22:57:39
栏目: 编程语言

在C语言中,静态链表是使用数组来实现的链表

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

#define MAX_SIZE 100 // 定义静态链表的最大容量

typedef struct Node {
    int data;          // 节点存储的数据
    int next;           // 指向下一个节点的索引
} Node;

Node static_linked_list[MAX_SIZE]; // 定义静态链表数组
int free_list[MAX_SIZE];           // 定义空闲节点列表
int free_count = 0;                 // 记录空闲节点的数量

// 初始化静态链表
void init() {
    for (int i = 0; i < MAX_SIZE; i++) {
        free_list[i] = i;
        static_linked_list[i].next = -1;
    }
    free_count = MAX_SIZE;
}

// 插入节点到静态链表头部
void insert(int data) {
    if (free_count == 0) {
        printf("静态链表已满,无法插入新节点\n");
        return;
    }
    int new_node_index = free_list[free_count - 1];
    free_count--;
    static_linked_list[new_node_index].data = data;
    static_linked_list[new_node_index].next = 0;
    if (static_linked_list[0].next != -1) {
        static_linked_list[new_node_index].next = static_linked_list[0].next;
    }
    static_linked_list[0].next = new_node_index;
}

// 删除静态链表中值为data的节点
void delete(int data) {
    int current = 0;
    while (static_linked_list[current].next != -1) {
        if (static_linked_list[static_linked_list[current].next].data == data) {
            int to_delete = static_linked_list[current].next;
            static_linked_list[current].next = static_linked_list[to_delete].next;
            free_list[free_count] = to_delete;
            free_count++;
            break;
        }
        current = static_linked_list[current].next;
    }
}

// 打印静态链表
void print() {
    int current = static_linked_list[0].next;
    while (current != -1) {
        printf("%d ", static_linked_list[current].data);
        current = static_linked_list[current].next;
    }
    printf("\n");
}

int main() {
    init();
    insert(1);
    insert(2);
    insert(3);
    print(); // 输出: 3 2 1
    delete(2);
    print(); // 输出: 3 1
    return 0;
}

这个示例中,我们定义了一个静态链表数组static_linked_list和一个空闲节点列表free_listinit函数用于初始化静态链表,insert函数用于在静态链表头部插入新节点,delete函数用于删除静态链表中值为data的节点,print函数用于打印静态链表。在main函数中,我们创建了一个静态链表,并插入了三个节点,然后删除了值为2的节点,并打印静态链表。

0