zoukankan      html  css  js  c++  java
  • 【计蒜课】【数据结构】【顺序表查找、删除、遍历操作的复习答案】

    #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--;
    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;
    }

  • 相关阅读:
    js闭包
    mysql 创建索引
    模拟title实现提示功能
    数组的深拷贝和浅拷贝
    JavaScript总结之DOM基本操作(三)
    JavaScript总结之数组操作(二)
    JavaScript总结之字符串操作(一)
    Visual Studio Code中JavaScript开发环境的配置
    PhpStorm+PhpStudy开发环境的配置
    如何在个人网站上添加logo图标
  • 原文地址:https://www.cnblogs.com/P201821430045/p/11826136.html
Copyright © 2011-2022 走看看