堆串-用c语言实现

#include 
#include 
#include 

// 函数声明
char *createHeapString(const char *str);// 创建堆串
void destroyHeapString(char *str);// 释放堆串内存
char *heapStringCopy(char *dest, const char *src);// 复制堆串
char *heapStringCat(char *dest, const char *src);// 连接堆串

int main() {
    // 创建堆串
    char *heapStr = createHeapString("Hello");
    printf("创建堆串: %s\n", heapStr);

    // 复制堆串
    char *copyStr = createHeapString("");
    copyStr = heapStringCopy(copyStr, heapStr);
    printf("复制堆串: %s\n", copyStr);

    // 连接堆串
    char *catStr = createHeapString("");
    catStr = heapStringCat(catStr, heapStr);
    catStr = heapStringCat(catStr, " World!");
    printf("连接堆串: %s\n", catStr);

    // 释放堆串内存
    destroyHeapString(heapStr);
    destroyHeapString(copyStr);
    destroyHeapString(catStr);

    return 0;
}

// 创建堆串
char *createHeapString(const char *str) {
    char *heapStr = (char *)malloc(strlen(str) + 1);//创建内存 
    if (heapStr != NULL) {
        strcpy(heapStr, str);
    }
    return heapStr;
}

// 释放堆串内存
void destroyHeapString(char *str) {
    free(str);
}

// 复制堆串
char *heapStringCopy(char *dest, const char *src) {
    if (dest != NULL) {
        free(dest); // 释放原有内存
    }
    dest = (char *)malloc(strlen(src) + 1);
    if (dest != NULL) {
        strcpy(dest, src);
    }
    return dest;
}

// 连接堆串
char *heapStringCat(char *dest, const char *src) {
    int newLength = strlen(dest) + strlen(src) + 1;
    dest = (char *)realloc(dest, newLength);
    if (dest != NULL) {
        strcat(dest, src);
    }
    return dest;
}

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