今天开始复习数据结构了,先从对数组的操作开始。
#include <stdio.h>
#include <sys/malloc.h>
#include <stdbool.h>
struct Arr //定义数组的数据结构
{
int * pBase;
int lenth;
int cnt;
};
void init(struct Arr * Array,int len)//初始化数组,使其拥有一块确切的内存
{
Array->pBase = (int *)malloc(sizeof(int)*len);//开辟一块动态内存使得pBase指向该连续内存(相当于数组的首地址)
Array->lenth = len;
Array->cnt = 0;
}
bool is_empty(struct Arr * Array)//判断数组是否为空
{
if(Array->cnt == 0)
return true;
else
return false;
}
bool is_full(struct Arr * Array)//判断数组是否已满
{
if(Array->cnt == Array->lenth)
return true;
else
return false;
}
void show_arr(struct Arr * Array)//显示数组中的数
{
int i;
if(is_empty(Array))
printf("数组为空!");
else
for(i=0;i<Array->cnt;i++)
printf("%d",Array->pBase[i]);
}
void append(struct Arr * Array,int val)//add功能.定义函数的时候,形参要写清楚数据类型
{
if(is_full(Array))//传参数的时候不用写数据类型
printf("数组已满!");
else
{
Array->pBase[Array->cnt] = val;
++Array->cnt;//pBase++ 指针自动指向下一个元素的
}
}
bool insert(struct Arr * Array,int pos,int val)//如果数组满了pos的值没有在1~pos之间,也返回pos.
{
int i;
if (is_full(Array))
return false;
if (pos<1 || pos>Array->cnt+1)
return false;
for (i=Array->cnt-1; i>=pos-1; --i)//从cnt处的元素开始向后退一个
{
Array->pBase[i+1] = Array->pBase[i];
}
Array->pBase[pos-1] = val;
(Array->cnt)++;//最后使cnt+1
return true;
}
void sort_arr(struct Arr * Array)//冒泡排序
{
int i, j, t;
for (i=0; i<Array->cnt; ++i)
{
for (j=i+1; j<Array->cnt; ++j)
{
if (Array->pBase[i] > Array->pBase[j])
{
t = Array->pBase[i];
Array->pBase[i] = Array->pBase[j];
Array->pBase[j] = t;
}
}
}
}
void invert(struct Arr * Array)//最后一个元素和第一个元素互换
{
int i = 0;
int j = Array->cnt-1;
int t;
while (i < j)
{
t = Array->pBase[i];
Array->pBase[i] = Array->pBase[j];
Array->pBase[j] = t;
++i;
--j;
}
return;
}
int main(void)
{
struct Arr arr;
init(&arr,6);
append(&arr,1);
append(&arr,2);
append(&arr,3);
insert(&arr,1,6);
show_arr(&arr);
return 0;
}
心得:试数很关键,不回的时候就试一些数字,就出来了.
明天继续链表.