串的堆表示

串的堆表示

示例代码

下面实现了基本的五种操作函数

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

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0

typedef int Status;

typedef struct 
{
    char * ch;
    int length;
}HString;

/* 生成一个其值等于chars的串T */
Status StrAssign(HString *T, char * chars)
{
    if(T->ch)
        free(T->ch);    /* 如果T不为空串 */
    int len;
    for(len=0; chars[len] != '\0'; len++)
        ;              /* 获取原串长度 */
    if(!len) {   
        T->ch = NULL;
        T->length = 0;
        return ERROR;
    }
    T->ch = (char *)malloc(len*sizeof(char));
    if(!T->ch) 
        return ERROR;
    T->length = len;
    for(len--; len>=0; len--)
        T->ch[len] = chars[len]; /* 复制原串 */
    return OK;
}

/* 返回串S的元素个数 */
int StrLength(HString S)
{
    return S.length;
}

/* 比较S,T,若S>T返回值>0 ,若S=T,返回0,若S<T,返回值<0 */
int StrCompare(HString S, HString T)
{
    for(int i=0; i<S.length && i<S.length; i++)
        if(S.ch[i] != T.ch[i])
            return S.ch[i] - T.ch[i];
    return S.length - T.length;
}

/* 清空字符串,并释放S所占的空间 */
Status ClearString(HString *S)
{
    if(S->ch) {
        free(S->ch);
        S->ch = NULL;
    }
    S->length = 0;
    return OK;
}

/* 用T返回由S1,S2拼接成的串 */
Status Concat(HString *T, HString S1, HString S2)
{
    if(T->ch)
        free(T->ch);    /* 释放旧空间 */
    T->ch = (char *)malloc( (S1.length + S2.length) * sizeof(char) );
    if(!T->ch)
        return ERROR;
    int i;
    for(i=0; i<S1.length; i++)
        T->ch[i] = S1.ch[i];        /* 复制串1 */
    for(int j=0; j<S2.length; j++,i++)
        T->ch[i] = S2.ch[j];        /* 复制串2 */
    T->length = i;
    return OK;
}


/* 打印串 */
void PrintStr(HString T)
{
    for(int i=0;i<T.length;i++) {
        printf("%c",T.ch[i]);
    }
    printf("\n");
}


int main()
{
    HString T,S1,S2;
    T.ch  = NULL;
    S1.ch  = NULL;
    S2.ch  = NULL;

    StrAssign(&S1,"BBC");
    StrAssign(&S2,"BBC");
    StrAssign(&T," I AM ROBOT");
    Concat(&T,S1,S2);
    PrintStr(S1);
    PrintStr(S2);
    PrintStr(T);
    printf("EQU %d\n",StrCompare(S2,S1));
    ClearString(&T);
    ClearString(&S1);
    ClearString(&S2);
    return 0;
}

posted @ 2019-10-06 18:37  wjundong  阅读(174)  评论(0编辑  收藏  举报