Searching, sorting and deduplication of the sequence table of the data structure learning series

  • Sequence lookup:
  • 数据元素的位置According to the sequence table 查找, the code is as follows:
  • Sample code:
int search_seq_list(list_t *seq_list,int pos,int *num){
    
    

    if(NULL == seq_list || NULL == num){
    
    

        printf("内存分配失败\n");

        return -1;

    }

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

        printf("查找位置不合理,查找失败\n");

        return -1;

    }

    *num = seq_list->a[pos].num;

    return 0;
}
  • Precautions:
  • 1. After the formal parameters are passed to the function with the function of finding data elements, it needs to be done 入参合理性检查, such as the formal parameters in the function seq_list和num;
  • 2. Judging whether the position of the data element to be searched is reasonable in the sequence table, if条件语句内容consistent with the function of deleting any position;
  • Sorting of the sequence table:
  • According to each in the sequence table 数据元素的大小, do data elements 冒泡排序, the code is as follows:
  • Sample code:
int sort_seq_list(list_t *seq_list){
    
    

    if(NULL == seq_list){
    
    

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

        return -1;

    }

    for(int i = 0 ; i < seq_list->count - 1; i++){
    
    

        for(int j = 0; j < seq_list->count - 1 - i; j++ ){
    
    

            if(seq_list->a[j].num > seq_list->a[j+1].num){
    
    

                data_t temp = seq_list->a[j];

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

                seq_list->a[j+1] = temp;

            }

        }
    }

    printf("本次排序结束\n");
    return 0;
}
  • Precautions:
  • 1. Define one 结构体变量,作为第三方变量, according to if条件语句, 交换两个数据元素的位置;
  • 2. Pay attention to cross-border issues, for example 第二层for循环, j < seq_list->count - 1 - i;in -1order 防止越界;
  • Deduplication of sequence table:
  • 剔除in sequence 重复的数据元素, for example:
11 33 55 55 66 66 66 66 
本次去重结束
11 33 55 66 
  • Sample code:
int del_rep_seq_list(list_t *seq_list){
    
    

    if(NULL == seq_list){
    
    

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

        return -1;

    }

    for(int i = 0; i < seq_list->count; i++){
    
    

        for(int j = i + 1; j < seq_list->count;){
    
    

                if(seq_list->a[i].num == seq_list->a[j].num){
    
    

                   for(int k = j; k < seq_list->count-1; k++){
    
    

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

                    }

                    seq_list->count--;

                } else {
    
    

                    j++;
                }

        }


    }

    printf("本次去重结束\n");

    return 0;
}
  • Precautions:
  • 1. 第二层for循环is to be in the sequence table 寻找相同的数据元素;
  • 2. Sequence table method and in 去重的具体操作sequence table ;任意位置删除数据元素操作一致

Guess you like

Origin blog.csdn.net/qq_41878292/article/details/132646603