块链存储实现串

#include 
#include 
#include 

// 定义块的大小
#define BLOCK_SIZE 4

// 节点结构定义
typedef struct Block {
    char data[BLOCK_SIZE]; // 数据域,存储字符
    struct Block *next;    // 指针域,指向下一个块
} Block;

// 创建新块的函数
Block *createBlock(const char *str) {
    Block *newBlock = (Block *)malloc(sizeof(Block));
    if (newBlock != NULL) {
        strncpy(newBlock->data, str, BLOCK_SIZE);
        newBlock->next = NULL;
    }
    return newBlock;
}

// 释放块链的函数
void freeBlockChain(Block *head) {
    Block *current = head;
    while (current != NULL) {
        Block *temp = current;
        current = current->next;
        free(temp);
    }
}

// 打印块链的函数
void printBlockChain(Block *head) {
    Block *current = head;
    while (current != NULL) {
        printf("%s", current->data);
        current = current->next;
    }
    printf("\n");
}

// 向块链末尾添加块的函数
void appendBlock(Block **head, const char *str) {
    Block *newBlock = createBlock(str);
    if (*head == NULL) {
        *head = newBlock;
    } else {
        Block *current = *head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newBlock;
    }
}

// 主函数
int main() {
    Block *head = NULL; // 初始化块链为空

    // 向块链中添加字符串
    appendBlock(&head, "Hello");
    appendBlock(&head, "Wor");
    appendBlock(&head, "ld!");

    // 打印块链
    printBlockChain(head); // 输出: HelloWorld!

    // 释放块链内存
    freeBlockChain(head);

    return 0;
}

你可能感兴趣的:(数据结构,算法)