• 计蒜课--顺序表查找、删除、遍历操作的复习


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

    #define ERROR 0
    #define OK 1

    typedef struct Vector {
    int size, length;
    int *data;
    } Vector;

    void init(Vector *vector, int size) {
    vector->size = size;
    vector->length = 0;
    vector->data = (int *)malloc(sizeof(int) * size);
    }

    void expand(Vector *vector) {
    int *old_data = vector->data;
    vector->size = vector->size * 2;
    vector->data = (int *)malloc(sizeof(int) * vector->size);
    for (int i = 0; i < vector->length; ++i) {
    vector->data[i] = old_data[i];
    }
    free(old_data);
    }

    int insert(Vector *vector, int loc, int value) {
    if (loc < 0 || loc > vector->length) {
    printf("failed ");
    return ERROR;
    }
    if (vector->length >= vector->size) {
    //return ERROR;
    expand(vector);
    }
    for (int i = vector->length; i > loc; --i) {
    vector->data[i] = vector->data[i - 1];
    }
    vector->data[loc] = value;
    vector->length++;
    printf("success ");
    return OK;
    }

    int search(Vector *vector, int value) {
    for (int i = 0; i < vector->length; ++i) {
    if (vector->data[i] == value) {
    printf("success ");
    return OK;
    }
    }
    printf("failed ");
    return ERROR;
    }

    int delete_node(Vector *vector, int index) {
    if (index < 0 || index >= vector->length) {
    printf("failed ");
    return ERROR;
    }
    for (int i = index + 1; i < vector->length; ++i) {
    vector->data[i - 1] = vector->data[i];
    }
    vector->length = vector->length - 1;
    printf("success ");
    return OK;
    }

    void print(Vector *vector) {
    for(int i=0;i<vector->length;++i){
    if(i>0){
    printf(" ");
    }
    printf("%d",vector->data[i]);

    }
    printf(" ");
    }

    void clear(Vector *vector) {
    free(vector->data);
    free(vector);

    }

    int main() {
    Vector *a = (Vector *)malloc(sizeof(Vector));
    init(a, 20);
    int m;
    int t;
    int x,y;
    scanf("%d",&m);
    while(m>=1 && m<=100){
    scanf("%d",&t);
    if(t == 4){
    print(a);
    }
    if(t == 1){
    scanf("%d %d",&x,&y);
    insert(a,x,y);
    }
    if(t == 2){
    scanf("%d",&x);
    delete_node(a,x);
    }
    if(t == 3){
    scanf("%d",&x);
    search(a,x);
    }
    m--;

    }
    clear(a);
    return 0;
    }

  • 相关阅读:
    解决winform DataGridView 绑定数字值列排序不对的问题
    C#中向数据库中添加注册新用户,并查询数据库中是否存在同名的用户。
    SQL数据库的脱机与联机操作
    odoo视频教程收集
    odoo10导入导出-转
    草稿-bom- 肥料生产
    freebsd 域名服务器
    freebsd启动报错:My unqualified host name unkown...Sleeping for retry.
    docker-freebsd-20150625
    supervisorctl error
  • 原文地址:https://www.cnblogs.com/p201821440027/p/11832057.html
Copyright © 2020-2023  润新知