溫馨提示×

c語言靜態鏈表的刪除操作

小樊
105
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_list。init函數用于初始化靜態鏈表,insert函數用于在靜態鏈表頭部插入新節點,delete函數用于刪除靜態鏈表中值為data的節點,print函數用于打印靜態鏈表。在main函數中,我們創建了一個靜態鏈表,并插入了三個節點,然后刪除了值為2的節點,并打印靜態鏈表。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女