#include <stdio.h>
#include <malloc.h>
#define InitSize 10
typedef struct{
int *data;
int MaxSize;
int length;
}SeqList;
void InitData(SeqList&); //初始化顺序表
void IncreaseSize(SeqList & , int); //增加顺序表长度
void InsertData(SeqList & , int , int); //插入数据
int DeleteData(SeqList & , int , int &); //删除数据
int SearchData(SeqList , int); //按位查找数据
int SearchNum(SeqList , int); //按值查找数据
int main(void){
SeqList line;
InitData(line); //初始化
IncreaseSize(line,5); //增加顺序表长度
InsertData(line,1,1); //插入数据
InsertData(line,2,2);
InsertData(line,3,3);
InsertData(line,4,4);
InsertData(line,5,5);
printf("当前顺序表中的数据是:"); //打印顺序表中数据
for(int i = 0 ; i < line.length ; i ++){
printf("%d ",line.data[i]);
}
printf("
");
int e = -1;
printf("删除的数据是:%d",DeleteData(line,2,e)); //删除数据
printf("
");
printf("当前顺序表中的数据是:"); //打印顺序表中数据
for(int i = 0 ; i < line.length ; i ++){
printf("%d ",line.data[i]);
}
printf("
");
printf("查找的数据是:%d",SearchData(line,2));
printf("
");
printf("查找的值在第%d位。",SearchNum(line,4));
return 0;
}
//初始化
void InitData(SeqList &L){
L.data = (int*)malloc(sizeof(int)*InitSize);
L.MaxSize = InitSize;
L.length = 0;
for(int i = 0 ; i < InitSize ; i ++){
L.data[i] = 0;
}
}
//增加顺序表长度
void IncreaseSize(SeqList &L , int len){
int *p = L.data;
L.data = (int*)malloc(sizeof(int)*(L.MaxSize+len));
for(int i = 0 ; i < L.length ; i ++){
L.data[i] = p[i];
}
L.MaxSize = L.MaxSize + len;
free(p);
}
//插入数据
void InsertData(SeqList &L , int m , int n){
for(int j = L.length ; j >= m ; j --){
L.data[j] = L.data[j-1];
}
L.data[m-1] = n;
L.length ++;
}
//删除数据
int DeleteData(SeqList &L , int m , int &n){
n = L.data[m-1];
for(int i = m ; i <= L.length ; i ++){
L.data[i-1] = L.data[i];
}
L.length --;
return n;
}
//按位查找
int SearchData(SeqList L , int m){
return L.data[m-1];
}
//按数值查找
int SearchNum(SeqList L , int n){
for(int i = 0 ; i < L.length ; i++){
if(L.data[i] == n){
return i+1;
}
}
return -1;
}