数组 线性表 线性 malloc 连续 个数 print 空间 位置
- /*
- 采用面向对象的方式进行分析
- Arr对象 保存动态创建数组的 首地址 数组长度 数组有效个数
- */
- #include < stdio.h >
- struct Arr {
- int * pBase; //存储数组第一个元素的地址
- int len; //数组的长度
- int cnt; //当前有效个数
- };
- void init(struct Arr * pArr, int length);
- bool append(struct Arr * pArr, int val);
- bool insert(struct Arr * pArr, int pos, int val);
- bool delete(struct Arr * pArr, int pos, int * pVal);
- bool isEmpty(struct Arr * pArr);
- bool isFull(struct Arr * pArr);
- void show(struct Arr * pArr);
- void inversion(struct Arr * pArr);
- int main(void) {
- struct Arr arr;
- int val;
- init( & arr, 6);
- append( & arr, 1);
- show( & arr);
- delete( & arr, 1, &val);
- /
- return 0;
- }
- / / 记住一句话:要想接收地址参数加 * 号void init(struct Arr * pArr, int length) {
- pArr - >pBase = (int * ) malloc(sizeof(int) * length);
- if (NULL == pArr - >pBase) {
- printf("分配内存失败\n");
- exit( - 1);
- } else {
- pArr - >len = length;
- pArr - >cnt = 0;
- }
- return;
- }
- void show(struct Arr * pArr) {
- //这里传pArr,而不是传&pArr 因为:真正要操作的是数组的地址
- //传递到isEmpty这个函数 相当于拷贝了一份pArr,但是pArr已经存储了数组的地址
- //如果传递&pArr 那么相当于把指针pArr的地址传递了过去 是不对滴 所以传递pArr
- if (isEmpty(pArr)) {
- printf("数组是空\n");
- } else {
- for (int i = 0; i < pArr.cnt; i++) {
- printf("%d ", pArr - >pBase[i]);
- printf("\n");
- }
- }
- }
- bool isEmpty(struct Arr * pArr) {
- if (0 == pArr - >cnt) {
- return true;
- } else {
- return false;
- }
- }
- bool isFull(struct Arr * pArr) {
- if (pArr - >cnt == pArr - >len) {
- return true;
- } else {
- return false;
- }
- }
- bool append(struct Arr * pArr, int val) {
- if (isFull(pArr)) {
- printf("数组满了,扩容去吧\n");
- return false;
- } else {
- pArr - >pBase[pArr - >cnt] = val;
- pArr - >cnt++;
- return true;
- }
- }
- bool insert(struct Arr * pArr, int pos, int val) {
- //如果pos=pArr->cnt相当于追加在最后,但是不能比cnt+1大,因为数组是连续空间
- if (isFull(pArr) || pos < 1 || pos > pArr - >cnt + 1) {
- return false;
- }
- int i;
- for (i = pArr - >cnt - 1; i >= pos - 1; i++) { //把 添加位置的坐标 到 最后 统一向后移动一位
- pArr - >pBase[i + 1] = pArr - >pBase[i];
- }
- pArr - >pBase[pos - 1] = val;
- pArr - >cnt++;
- return true;
- }
- bool delete(struct Arr * pArr, int pos, int * pVal) {
- if (isFull(pArr) || pos < 1 || pos > pArr - >cnt) {
- return false;
- }
- int i; * pVal = pArr - >pBase[pos - 1];
- for (i = pos; i < pArr - >cnt; i++) { //把指定位置之后的值 统一向前进一位
- pArr - >pBase[i - 1] = pArr - >pBase[i];
- }
- pArr - >cnt--;
- return true;
- }
- void inversion(struct Arr * pArr) {
- int i = 0;
- int j = pArr - >cnt - 1;
- int t;
- while (i < j) {
- t = pArr - >pBase[i];
- pArr - >pBase[i] = pArr - >pBase[j];
- pArr - >pBase[j] = t;
- i++;
- j--;
- }
- return;
- }
线性表
数组 线性表 线性 malloc 连续 个数 print 空间 位置
原文:https://www.cnblogs.com/weishao-lsv/p/8150995.html
来源: http://www.bubuko.com/infodetail-2445629.html