模块一:线性结构(所有的节点可以用一根线穿起来,首节点前没有节点,尾节点后没有节点,中间节点前后只有一个节点)
连续存储(数组)
离散存储(链表)
线性结构的两种常见应用之一:栈
线性结构的两种常用应用之一:队列
动态数组的构建和操作(添插删序)
#include <stdio.h>
#include<malloc.h>//包含malloc函数
#include<stdlib.h>//包含了exit函数
struct Array
{
int len;//数组的长度
int * a;//数组的首单元的地址
int cnt;//当前数组的有效长度
};
void init_arr(struct Array *p,int len)
{
p->len = 10;
p->cnt = 0;
p->a = (int *)malloc(sizeof(int)*len);
if(p->a == NULL)
{
printf("动态内存分配失败!\n");
exit(-1);
}
}
bool is_full(struct Array *p)
{
if(p->cnt == p->len)
return true;
else
return false;
}
bool is_empty(struct Array *p)
{
if(p->cnt == 0)
return true;
else
return false;
}
bool append(struct Array *p,int x)
{
int i;
if (is_full(p))
return false;
else
{
i = p->cnt;
p->a[i] = x;
}
p->cnt++;
return true;
}
bool insert(struct Array *p,int pos,int x)//pos是插入的位置,从1开始,在pos的前面插入
{
if (pos<1||pos>p->cnt+1)
return false;
else
{
int i;
for(i=p->cnt-1;i>=pos-1;--i)
{
p->a[i+1] = p->a[i];
}
p->a[pos-1] = x;
}
p->cnt++;
return true;
}
void show_arr(struct Array *p)
{
if (is_empty(p))
printf("数组为空!\n");
else
for(int i = 0;i<p->cnt;++i)
{
printf("%d ",p->a[i]);
}
printf("\n");
}
void invert_arr(struct Array *p)
{
int t;
int i = 0;
int j = p->cnt-1;
while(i<j)
{
t = p->a[i];
p->a[i] = p->a[j];
p->a[j] = t;
i++;
j--;
}
}
sort_arr(struct Array *p)
{
int t;
for(int i = 0;i<p->cnt-1;i++)
for(int j = i+1;j<p->cnt;j++)
if(p->a[i]>p->a[j])
{
t = p->a[i];
p->a[i] = p->a[j];
p->a[j] = t;
}
}
bool del_arr(struct Array *p,int pos,int *del_val)
{
if(is_empty(p))
{
printf("数组为空!");
return false;
}
if (pos<1||pos>p->cnt+1)
return false;
*del_val = p->a[pos-1];
for(int i=pos;i<=p->cnt-1;i++)
{
p->a[i-1] = p->a[i];
}
p->cnt--;
return true;
}
int main(void)
{
struct Array a;
int len = 10;
int del_val;
init_arr(&a,len);
append(&a,2);
append(&a,5);
append(&a,3);
append(&a,8);
append(&a,6);
append(&a,1);
show_arr(&a);
insert(&a,2,9);
show_arr(&a);
del_arr(&a,4,&del_val);
show_arr(&a);
printf("删除的元素是: %d\n",del_val);
invert_arr(&a);
show_arr(&a);
sort_arr(&a);`在这里插入代码片`
show_arr(&a);
return 0;
}