15.3顺序查找(线性查找),顺序表用指针方式实现

#include 
#include 
#include 

typedef int ElemType;
typedef struct {
    ElemType *ele;
    int length;
} Table;

void initTable(Table &table, int length) {
    table.ele = (ElemType *) malloc(sizeof(ElemType) * length);
    table.length = length;
    srand(time(NULL));
    for (int i = 0; i < table.length; i++) {
        table.ele[i] = rand() % 100;
    }
}

void printTable(Table table) {
    for (int i = 0; i < table.length; i++) {
        printf("%3d",table.ele[i]);
    }
}
void search(Table table, int key) {
    for (int i = 0; i < table.length; i++) {
        if (table.ele[i] == key) {
            printf("%d", i+1);
        }
    }
}

int main() {
    Table table;
    int key;
    initTable(table, 5);
    printTable(table);
    scanf("%d",&key);
    search(table, key);
    return 0;
}

你可能感兴趣的:(考研C,C++数据结构,数据结构)