#include <stdio.h>
#include <stdlib.h>
#define Size 5
typedef struct SequenceTable
{
int * head;
int length;
int size;
} SequenceTable;
SequenceTable initTable(){
SequenceTable st;
st.head = (int*)malloc(Size * sizeof(int));
if(!st.head){
printf("init failed!\n");
exit(0);
}
st.length = 0;
st.size = Size;
return st;
}
SequenceTable addTable(SequenceTable st, int elem, int add){
if(add > st.length + 1 || add < 1){
printf("insert seat have error!");
return st;
}
if(st.length >= st.size){
st.head= (int *)realloc(st.head, (st.size + 1) * sizeof(int));
if(!st.head){
printf("save space assign error!");
}
st.size += 1;
}
for(int i = st.length-1;i>=add-1;i--){
st.head[i+1]=st.head[i];
}
st.head[add-1]=elem;
st.length ++;
return st;
}
SequenceTable delTable(SequenceTable t, int add){
if(add > t.length || add < 1){
printf("delete element seat is error!");
return t;
}
for(int i=add;i<t.length;i++){
t.head[i-1]=t.head[i];
}
t.length --;
return t;
}
int selectTable(SequenceTable t, int elem){
for(int i=0;i<t.length;i++){
if(t.head[i] == elem){
return i+1;
}
}
return -1;
}
SequenceTable amendTable(SequenceTable t, int elem, int newElem){
int add = selectTable(t, elem);
t.head[add - 1] = newElem;
return t;
}
void displayTable(SequenceTable t){
for(int i=0;i<t.length;i++){
printf("%d ", t.head[i]);
}
printf("\n");
}
int main(){
SequenceTable t1 = initTable();
for(int i=1;i<=Size;i++){
t1.head[i-1]=i;
t1.length++;
}
printf("the source sequence table: \n");
displayTable(t1);
printf("delete element 1: \n");
t1 = delTable(t1, 1);
displayTable(t1);
printf("insert the element '5' at the secend seat:\n");
t1 = addTable(t1, 5, 2);
displayTable(t1);
printf("find the element '3' seat:\n");
int add = selectTable(t1, 3);
printf("%d\n", add);
printf("change element '3' to '6':\n");
t1 = amendTable(t1, 3, 6);
displayTable(t1);
return 0;
}