# include <stdio.h> # include <stdbool.h> # include <stdlib.h> struct Arr{ int * pBase; int len; int count; }; void init_arr(struct Arr *, int); bool bool_empty_arr(struct Arr *); bool bool_full_arr(struct Arr *); bool bool_append_arr(struct Arr *, int); bool bool_insert_arr(struct Arr *, int, int); bool bool_delete_arr(struct Arr *, int); void reverse_arr(struct Arr *); void sort_arr(struct Arr *); void show_arr(struct Arr *); int main (void){ struct Arr arr;// 这里能不能用 指针???? init_arr(&arr, 5); bool_empty_arr(&arr); bool_append_arr(&arr, 1); bool_append_arr(&arr, 3); bool_append_arr(&arr, 2); // bool_append_arr(&arr, 4); // bool_append_arr(&arr, 5); // bool_append_arr(&arr, 6); bool_insert_arr(&arr, 4, 99); bool_delete_arr(&arr, 3); show_arr(&arr); reverse_arr(&arr); show_arr(&arr); sort_arr(&arr); show_arr(&arr); return 0; } void init_arr(struct Arr * pArr, int length){ pArr->pBase = (int *) malloc(sizeof(int) * length); if(pArr->pBase == NULL){ printf("录入失败!请重新录入\n"); exit(-1); } else{ pArr->len = length; pArr->count = 0; } } bool bool_empty_arr(struct Arr * pArr){ if(pArr->count == 0){ printf("数据库为空,可以填加数据!\n"); return true; } else{ return false; } } void show_arr(struct Arr * pArr){ if(bool_empty_arr(pArr)){ printf("无数据!\n"); } else{ for (int i = 0; i < pArr->count; ++i) printf("%d ", pArr->pBase[i]); printf("\n"); } } bool bool_full_arr(struct Arr * pArr){ if(pArr->count == pArr->len){ return true; } else{ return false; } } bool bool_append_arr(struct Arr * pArr, int num){ if(bool_full_arr(pArr)){ printf("数据库满!\n"); return false; } pArr->pBase[pArr->count] = num; (pArr->count)++; return true; } bool bool_insert_arr(struct Arr * pArr, int pos, int num){ if(bool_full_arr(pArr)){ printf("插入失败,数据库满!\n"); return false; } if(pos < 1 || pos > (pArr->count)+1){ printf("插入位置出错!error:%d\n", pos); return false; } for(int i = (pArr->count)-1; i >= pos-1; i--){ pArr->pBase[i+1] = pArr->pBase[i]; } pArr->pBase[pos-1] = num; pArr->count++; return true; } bool bool_delete_arr(struct Arr * pArr, int pos){ if(bool_empty_arr(pArr)){ printf("数据库为空,无法删除!"); return false; } int * pVal = &(pArr->pBase[pos-1]); if(pos < 1 || pos > pArr->count){ printf("删除位置出错!error:%d\n", pos); return false; } else{ printf("删除成功,您删除的数据:%d\n", * pVal); } for (int i = pos; i <= pArr->count; ++i) { pArr->pBase[i-1] = pArr->pBase[i]; } pArr->count--; return true; } void reverse_arr(struct Arr * pArr){ int i = 0; int j = (pArr->count)-1; int t; while (i < j){ t = pArr->pBase[i]; pArr->pBase[i] = pArr->pBase[j]; pArr->pBase[j] = t; i++; j--; } printf("倒置后的数据:\n"); } void sort_arr(struct Arr * pArr){ for (int i = 0; i < (pArr->count)-1; ++i) { bool flag = false; for (int j = i+1; j < pArr->count; ++j) { if(pArr->pBase[i] > pArr->pBase[j]){ int t = pArr->pBase[i]; pArr->pBase[i] = pArr->pBase[j]; pArr->pBase[j] = t; flag = true; } } if(!flag) break; } printf("排序后的数据:\n"); }
数据结构//C——动态分配—连续存储(数组)
于 2022-01-21 15:30:22 首次发布