数据结构(C语言版):1 顺序表

1 顺序表

#include 
#include 

typedef struct seqList { // 结构名
    char *headP;
    int length;
    int size;
} SeqList; // 结构别名

SeqList initSeqList() {
    SeqList seq;
    seq.headP = (char *) malloc(10 * sizeof(char)); // 创建数组
    seq.length = 0;
    seq.size = 10;
    return seq;
} 

void printSeqList(SeqList seq) {
    for (int i = 0; i < seq.length; ++i) {
        printf("%c,", seq.headP[i]);
    }
    printf("\n");
}

SeqList insertSeqList(SeqList *seq, char element, int position) {
    if (position > seq->length + 1 || position < 1) {
        printf("选择插入的位置有问题!");
        return *seq;
    }
    // 如果顺序表已满,则新增加内存
    if (seq->length == seq->size) {
        seq->headP = realloc(seq->headP, (seq->size + 1) * sizeof(char));
    }
    if (position == seq->length) {
        seq->headP[seq->length] = element;
    }
    for (int i = 0; i <= seq->length - position; ++i) {
        seq->headP[seq->length - i] = seq->headP[seq->length - (i + 1)];
    }
    seq->headP[position - 1] = element;
    seq->length = seq->length + 1;
    return *seq;
}

/**
 * 传值调用和引用调用
 */
SeqList removeSeqList(SeqList *seq, int position) {
    if (position > seq->length || position < 1) {
        printf("选择刪除的位置有问题!");
        return *seq;
    }
    for (int i = position; i < seq->length; ++i) {
        seq->headP[i - 1] = seq->headP[i];
    }
    seq->headP[seq->length - 1] = 0;
    seq->length = seq->length - 1;
    return *seq;
}

int findSeqList(SeqList seq, char element) {
    for (int i = 0; i < seq.length; ++i) {
        if (element == seq.headP[i]) {
            return i; // 返回下角标
        }
    }
    return -1; // 沒有查找到
}

SeqList modifySeqList(SeqList *seq, char oldElement, char newElement) {
    int index = findSeqList(*seq, oldElement);
    seq->headP[index] = newElement;
    return *seq;
}

void main() {
    SeqList seq = initSeqList();
    for (int i = 0; i < seq.size; ++i) {
        seq.headP[i] = 'a' + i;
        seq.length = seq.size;
    }
    printSeqList(seq);

    removeSeqList(&seq, 5);
    printSeqList(seq);

    insertSeqList(&seq, 'w', 5);
    printSeqList(seq);

    int index = findSeqList(seq, 'y');
    printf("下角标为:%d\n", index);

    modifySeqList(&seq, 'c', 'z');
    printSeqList(seq);
}

你可能感兴趣的:(数据结构(C语言版):1 顺序表)