1.顺序表的定义之静态分配
#include <stdio.h>
#define max 10
typedef struct {
int date[max];
int length;
}biao;//静态分配
void chushi(biao &L){
L.length=0;//初始化
}
int main(){
biao L;
chushi(L);
for(int i=0;i<max;i++){//循环输出顺序表中的元素
L.date[i]=i;//在顺序表中放入元素
printf("date[%d]=%d\n",i,L.date[i]);
}
return 0;
}
2.顺序表的定义之动态分配
#include <stdio.h>
#include <cstdlib>
#define max 10
typedef struct {
int *date;
int maxsize;//最大长度
int length;//当前长度
}biao;
void chushi(biao *L){//初始化,需要更改数据时用*,只是调用数据则不用
L->date=(int *)malloc(max*sizeof(int)); //用malloc函数申请一片连续的内存空间,前面的(int *)是强转
L->length=0;//有*时用->;&用.
L->maxsize=max;
}
void zhengjia(biao *L,int len){//输入原表和要增加的长度
int *p=L->date;//使p指针指向date的位置
L->date=(int *) malloc((max+len)*sizeof(int));
for(int i=0;i<L->length;i++){
L->date[i]=p[i];//将原表中的值放入新表中
}
L->maxsize=max+len;
free(p);//释放p的空间
}
int main(){
biao L;
chushi(&L);//前面有*,输入时则加入&
//省略一堆给表中赋值的代码
zhengjia(&L,5);//增加5个单位
return 0;
}
3.顺序表插入
#define max 10
typedef struct {
int date[max];
int length;//当前长度
}biao;
bool charu(biao &L,int i,int e){//插入的表,位置,数据
if(i<1||i>L.length+1){
return false;
}
if(L.length>=max){
return false;
}
for(int j=L.length;j>=i;j--)//插入时由最后一个元素往后移
{
L.date[j+1]=L.date[j];
}
L.date[i]=e;//将插入的值放入
L.length++;
return true;
}
4.顺序表删除
#include <stdio.h>
#include <cstdlib>
#define max 10
typedef struct {
int date[max];
int length;//当前长度
}biao;
bool charu(biao &L,int i,int &e){//删除的表,位置
if(i<1||i>L.length+1){
return false;
}
e=L.date[i-1];//被删除的元素赋给e
for(int j=i;j<L.length;j++)//删除时删除位置后的元素往前移
{
L.date[j-1]=L.date[j];
}
L.length--;
return true;
}
5.顺序表查找之按位查找
#include <stdio.h>
#include <cstdlib>
#define max 10
typedef struct {
int date[max];
int length;//当前长度
}biao;
int locate(biao &L,int i){
if(i<1||i>L.length){
printf("请输入正确位置");
} else{
return L.date[i-1];
}
}
6.顺序表之按值查找
#include <stdio.h>
#include <cstdlib>
#define max 10
typedef struct {
int *date;
int maxsize;
int length;//当前长度
}biao;
void chushi(biao &L){
L.date=(int *) malloc(L.length*sizeof(int));
L.length=0;
L.maxsize=max;
}
int wei(biao &L,int i){
return L.date[i-1];
}
int locate(biao &L,int e){//按值查找
for(int i=0;i<L.length;i++){
if (L.date[i]==e){
return i+1;
}
}
return 0;
}
int mai(){
biao L;
chushi(L);
wei(L,5)//查找位置为5的值
locate(L,5);//查找值为5的位置
}