#include
#include
#define MAXSIZE 1024
typedef int datatype;
struct sl{
datatype data[MAXSIZE];
int last;
};
int length(struct sl *list);
datatype get(struct sl *list, int i);
int find(struct sl *list, datatype e);
void insert(struct sl *list, datatype e, int i);
void del(struct sl *list, int i);
void display(struct sl *list);
int main(){
struct sl *list;
int i, e;
// dynamically allocate a piece of memory for the sequential list
list = (struct sl*)malloc(sizeof(struct sl));
// initialize the list
list->last = 9;
for (i=0; i<=list->last; i++){
list->data[i] = i*2;
}
printf("The length of the sequential list is: %d\n", length(list));
i=5;
printf("The element in the position %d is %d\n", i, get(list, i));
e=10;
printf("The position of the element %d is %d\n", e, find(list, e));
printf("\nThe original list is\n");
display(list);
i=1;
e=100;
insert(list, e, i);
printf("After insert 100 in 1, the list becomes: \n");
display(list);
i=5;
del(list, i);
printf("After delete the element in 5, the list becomes: \n");
display(list);
}
// return the length of the sequential list
int length(struct sl *list){
return list->last;
}
// returns the element in the position i
// Note: the position in a sequential list is its index
// if the input i is not valid, return 0
datatype get(struct sl *list, int i){
if (i > list->last)
return 0;
else
return list->data[i];
}
// return the position of the element e
// if the element e is not in the list, return -1
int find(struct sl *list, int e){
int i;
for (i = 0; i < list->last; i++)
if(e == list->data[i])
return i;
return -1;
}
// output the elements in order
void display(struct sl *list){
int i;
for(i = 0; i < list->last; i++)
printf("%d ", list->data[i]);
printf("\n");
}
// insert the element e in the position i
// check for the validation of the input i
void insert(struct sl *list, int e, int i){
int pos;
for(pos = list->last; pos >= i; pos--)
list->data[pos] = list->data[pos - 1];
list->data[pos] = e;
list->last++;
}
// delete the element in the position i
// check for the validation of the input i
void del(struct sl *list, int i){
int pos;
for(pos = i; pos < list->last; pos++)
list->data[pos] = list->data[pos + 1];
list->last--;
}
输出结果
The length of the sequential list is: 9
The element in the position 5 is 10
The position of the element 10 is 5
The original list is
0 2 4 6 8 10 12 14 16
After insert 100 in 1, the list becomes:
100 0 2 4 6 8 10 12 14 16
After delete the element in 5, the list becomes:
100 0 2 4 6 10 12 14 16