数据结构学习笔记(一)
假期以来我都坚持每天看一点郝斌的数据结构视频。讲的很透彻,也很风趣。
前几天都是为讲数据结构而做准备,讲了一些结构体和指针,今天终于开始正式将数据结构。说实话,我今天才知道函数的用处。。
照着郝斌讲连续存储数组的算法演示,又自己写了一遍,发现有一个错误,左看右看都看不出哪错了,索性贴出了,,,有兴趣的朋友可以看看
百度求助,一位牛人看出错误来,谢谢了!重新贴出正确的代码
- #include<stdio.h>
- #include<malloc.h>
- #include<stdlib.h>//包含exit
- intval,i,t;
- structArr
- {
- int*pBase;//储存的是数组第一个元素的地址
- intlen;//数组所能容纳的最大元素个数
- intcnt;//当前数组有效个数
- };
- voidinit_arr(structArr*pArr,intlength);//初始化
- boolappend_arr(structArr*pArr,intval);
- boolinsert_arr(structArr*pArr,intpos,intval);//pos的值从1开始
- booldelete_arr(structArr*pArr,intpos,int*pVal);
- intget();
- boolis_empty(structArr*pArr);
- boolis_full(structArr*pArr);
- voidsort_arr(structArr*pArr);
- voidshow_arr(structArr*pArr);
- voidinversion_arr(structArr*pArr);//倒置
- intmain()
- {
- structArrarr;
- init_arr(&arr,6);
- show_arr(&arr);
- append_arr(&arr,1);
- append_arr(&arr,2);
- append_arr(&arr,3);
- append_arr(&arr,4);
- delete_arr(&arr,1,&val);
- return0;
- }
- voidinit_arr(structArr*pArr,intlength)
- {
- pArr->pBase=(int*)malloc(sizeof(int)*length);
- if(NULL==pArr->pBase)
- {
- printf("动态内存分配失败!\n");
- exit(-1);//终止整个程序
- }
- else
- {
- pArr->len=length;
- pArr->cnt=0;
- }
- return;
- }
- boolis_empty(structArr*pArr)
- {
- if(0==pArr->cnt)
- returntrue;
- else
- returnfalse;
- }
- boolis_full(structArr*pArr)
- {
- if(pArr->cnt==pArr->len)
- returntrue;
- else
- returnfalse;
- }
- voidshow_arr(structArr*pArr)
- {
- if(is_empty(pArr))//pArr本来就是地址
- {
- printf("数组为空\n");
- }
- else
- {
- for(inti=0;i<pArr->cnt;++i)
- printf("%d",pArr->pBase[i]);
- printf("\n");
- }
- }
- boolappend_arr(structArr*pArr,intval)
- {
- if(is_full(pArr))
- returnfalse;
- else
- pArr->pBase[pArr->cnt]=val;
- (pArr->cnt)++;
- returntrue;
- }
- boolinsert_arr(structArr*pArr,intpos,intval)
- {
- inti;
- if(pos<1||pos>pArr->len)
- for(i=pArr->cnt-1;i>=pos-1;--i)
- {
- pArr->pBase[i+1]=pArr->pBase[i];
- }
- pArr->pBase[pos-1]=val;
- returntrue;
- }
- booldelete_arr(structArr*pArr,intpos,int*pVal)
- {
- if(is_empty(pArr))
- returnfalse;
- if(pos<1||pos>pArr->cnt)
- returnfalse;
- *pVal=pArr->pBase[pos-1];
- for(i=pos;i<pArr->cnt;i++)
- {
- pArr->pBase[i-1]=pArr->pBase[i];
- }
- pArr->cnt--;
- returntrue;
- }
- voidinversion_arr(structArr*pArr)
- {
- inti=0;
- intj=pArr->cnt-1;
- intt;
- while(i<j)
- {
- t=pArr->pBase[i];
- pArr->pBase[i]=pArr->pBase[j];
- pArr->pBase[j]=t;
- i++;
- j--;
- }
- return;
- }
- voidsort_arr(structArr*pArr)
- {
- inti,j;//冒泡法
- for(i=0;i<pArr->cnt;i++)
- {
- for(j=i+1;j<pArr->cnt;i++)
- {
- if(pArr->pBase[i]>pArr->pBase[j])
- {
- t=pArr->pBase[i];
- pArr->pBase[i]=pArr->pBase[j];
- pArr->pBase[j]=t;
- }
- }
- }
- }