数据结构学习系列之顺序表的两种插入方式

  • 方式1:
  • 在顺序表末端插入数据元素,代码如下:
  • 示例代码:
int insert_seq_list_1(list_t *seq_list,int data){
    
    

    if(NULL == seq_list){
    
    

        printf("入参为NULL\n");

        return -1;

    }

    if(N == seq_list->count){
    
    

        printf("顺序表已满,插入失败\n");

        return -1;

    }

    seq_list->a[seq_list->count].num = data;
    seq_list->count++;

    return 0;

}
  • 注意事项:

  • 1.形参传入到具有插入数据元素功能的函数后,需要做入参合理性检查

  • 2.还需要判断此时顺序表所存储的数据元素是否已满

  • 3.本示例代码中的count是计数的变量每次插入一个数据元素后,需要加1,此处易忽略

  • 方式2:

  • 在顺序表的任意位置插入数据元素,代码如下:

  • 示例代码:

int insert_seq_list_2(list_t *seq_list,int pos, int data){
    
    


    if(NULL == seq_list){
    
    

        printf("入参为NULL\n");

        return -1;

    }
    if(N == seq_list->count){
    
    

        printf("顺序表已满,插入失败\n");

        return -1;

    }
    if( pos < 0 || pos > seq_list->count){
    
    

        printf("插入位置不合理,插入失败\n");

        return -1;

    }

    int i = 0;
    i = seq_list->count-1;

    while(i >= pos){
    
    

        seq_list->a[i+1] = seq_list->a[i];

        i--;

    }

    seq_list->a[pos].num = data;
    seq_list->count++;

    return 0;
}
  • 注意事项:
  • 1.同方式1:形参传入到具有插入数据元素功能的函数后,需要做入参合理性检查
  • 2.也同方式1:还需要判断此时顺序表所存储的数据元素是否已满
  • 3.判断所要插入数据元素的位置在顺序表中是否合理
  • 4.可以采用while循环或者for循环的方式找到所要插入数据元素的位置后,此位置的数据元素以及此位置之后的所有数据元素,依次向后挪动一个位置,目的是腾出所指定的待插入位置
  • 5.将所要插入的数据元素的值赋值给该位置的值,也就是覆盖,记得count加1

猜你喜欢

转载自blog.csdn.net/qq_41878292/article/details/132639046
今日推荐