记录考研数据结构学习过程中的代码实现
(参考天勤书本)
#include<stdio.h>
#define Maxsize 100
typedef struct {
int data[Maxsize];
int length;
}Sqlist;
void initList(Sqlist &L){//初始化顺序表
L.length = 20;
}
int getElem(Sqlist L, int p, int &e){//求指定位置元素
if(p < 0 || p > L.length)
return 0;
e = L.data[p];
return 1;
}
int findElem(Sqlist L, int x){//从小到大寻找合适的插入位置
int i;
for(i = 0; i < L.length; i++){
if(L.data[i] >= x) return i;
}
return i;
}
int insertElem1(Sqlist &L, int p, int e){//在指定位置插入数据
int i;
if(p < 0 || p > L.length || L.length == Maxsize)
return 0;
for(i = L.length - 1; i >= p; i --){
L.data[i + 1] = L.data[i];
}
L.data[p] = e;
L.length ++;
return 1;
}
void insertElem2(Sqlist &L, int x){//按照顺序排序找到合适的插入位置
int p, i;
p = findElem(L, x);
for(i = L.length - 1; i >= p; i--){
L.data[i+1] = L.data[i];
}
L.data[p] = x;
L.length++;
}
int deleteElem(Sqlist &L, int p, int &e){//删除顺序表L中下标为p的元素,成功返回1,否则返回0 并将删除元素赋值给e
int i;
if(p < 0 || p > L.length)
return 0;
e = L.data[p];
for(i = p; i < L.length; i++){
L.data[i] = L.data[i + 1];
}
L.length --;
return 1;
}
int main(){
Sqlist L;
initList(L);
int i, n;
for(i = 0; i < L.length; i++){
L.data[i] = i;
printf(" %d", L.data[i]);
}
printf("\n please input the number to insert:");//自动排序插入测试
scanf("%d",&n);
insertElem2(L, n);
for(i = 0; i < L.length; i++){
printf(" %d", L.data[i]);
}
int p1, e;
printf("\n please input the number and place to insert:");//指定位置插入测试
scanf("%d %d",&p1,&e);//输入位置和插入值
insertElem1(L, p1, e);
for(i = 0; i < L.length; i++){
printf(" %d", L.data[i]);
}
int p2;
printf("\n please input the place to delete:");//指定位置插入测试
scanf("%d",&p2);//输入位置和插入值
deleteElem(L, p2, e);
for(i = 0; i < L.length; i++){
printf(" %d %d", L.data[i], e);
}
return 0;
}