C言語実装Listのデータ構造(詳細コメント)
11798 ワード
#include
#include //
#include //exit
#include //
struct Arr
{
int *pBase;//
int len;//
int cnt;//
//
};
void show_arr(struct Arr *pArr);// ,
void init_arr(struct Arr *pArr, int length);//
bool is_empty(struct Arr *pArr);//
bool append_arr(struct Arr *pArr, int val);// , ,
bool is_full(struct Arr *pArr);//
bool delete_arr(struct Arr *pArr, int pos, int *pVal);//
bool insert_arr(struct Arr *pArr, int pos, int val); // pos 1
void sort_arr(struct Arr *pArr);//
void innversion_arr(struct Arr *pArr);//
int main(void)
{
printf("%s
", "start");
struct Arr arr;
init_arr(&arr,6);
append_arr(&arr, 1);
append_arr(&arr, 21);
append_arr(&arr, 3);
append_arr(&arr, 4);
insert_arr(&arr,5,6);
append_arr(&arr, 5);
int val;
int posi = 2;
/** **/
/* if (delete_arr(&arr, posi, &val)) {
printf(" ");
printf("%d
",val);
}
else {
printf("%s
"" ");
}
*/
sort_arr(&arr);
innversion_arr(&arr);
show_arr(&arr);
/*int len;
printf("%s
","please input :len=");
scanf("%d",&len);
//(int?*) , pArr 。
int *pArr = (int *)malloc(sizeof(int)*len);*/
printf("%s
", "end");
getchar();
return 0;
}
void innversion_arr(struct Arr *pArr)//
{
int i = 0;
int j = pArr->cnt - 1;
int t;
while (ipBase[i];
pArr->pBase[i] = pArr->pBase[j];
pArr->pBase[j] = t;
++i;
--j;
}
return;
}
void sort_arr(struct Arr *pArr)// , , 2 ,
{
int i, j, t;
for (i = 0; i < pArr->cnt; ++i)
{
for (j = i + 1; j < pArr->cnt; ++j)
{
if (pArr->pBase[i] > pArr->pBase[j])
{
t = pArr->pBase[i];
pArr->pBase[i] = pArr->pBase[j];
pArr->pBase[j] = t;
}
}
}
}
bool insert_arr(struct Arr *pArr, int pos, int val) { //pos 1
int i;
if (is_full(pArr))
return false;
if (pos<1 || pos>pArr->cnt + 1) // 1 ( ) false
return false;
for (i = pArr->cnt - 1; i >= pos - 1; --i)// pos-1
{
pArr->pBase[i + 1] = pArr->pBase[i];//pos
}
pArr->pBase[pos - 1] = val; //
(pArr->cnt)++; //
}
bool delete_arr(struct Arr *pArr, int pos, int *pVal) {
int i;
if (is_empty(pArr))
return false;//
if (pos<1 || pos > pArr->cnt)
return false;//
*pVal = pArr->pBase[pos - 1];// pVal
for (i = pos; icnt; ++i)
{
pArr->pBase[i - 1] = pArr->pBase[i];//pos
}
(pArr->cnt)--; //
return true;
}
bool append_arr(struct Arr *pArr, int val)// , ,
{
// false
if (is_full(pArr))
return false;
//
pArr->pBase[pArr->cnt] = val;
(pArr->cnt)++;
return true;
}
bool is_full(struct Arr *pArr)//
{
if (pArr->cnt == pArr->len) {
printf("%s
", " ");
return true;
}
else
{
return false;
}
}
void show_arr(struct Arr *pArr)//
{
// if( )
//
// else
//
if (is_empty(pArr)) //
{
printf(" !
");
}
else
{
for (int i = 0; icnt; i++)
printf("%d
", pArr->pBase[i]);
printf("
");
}
}
bool is_empty(struct Arr *pArr)//
{
if (0 == pArr->cnt)
return true;
else
return false;
}
void init_arr(struct Arr *pArr, int length) {
//
pArr->pBase = (int*)malloc(sizeof(int)*length);
if (NULL == pArr->pBase)
{
printf("free error !
");
exit(-1);//
}
else
{
pArr->len = length;
pArr->cnt = 0;
printf("free !
");
}
return;
}