#include <stdio.h>
#include <stdlib.h>
#define Size 5
typedef struct SequenceTable
{
int * head;
int length;
int size;
} SequenceTable;
/**
* @brief 初始化顺序表
*
* @return 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;
}
/**
* @brief 向顺序表中添加元素
*
* @param st 要添加元素的目标顺序表
* @param elem 要插入的元素
* @param add 插入位置
* @return SequenceTable
*/
SequenceTable addTable(SequenceTable st, int elem, int add){
// to judge the insert seat have problam
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;
}
/**
* @brief 从顺序表中删除元素
*
* @param t 需要删除元素的顺序表
* @param add 删除元素的位置
* @return SequenceTable
*/
SequenceTable delTable(SequenceTable t, int add){
if(add > t.length || add < 1){
printf("delete element seat is error!");
return t;
}
// delete operation
for(int i=add;i<t.length;i++){
t.head[i-1]=t.head[i];
}
t.length --;
return t;
}
/**
* @brief 从给定的顺序表中查找指定元素并返回元素所在位置
*
* @param t 给定的顺序表
* @param elem 要查找的元素
* @return int
*/
int selectTable(SequenceTable t, int elem){
for(int i=0;i<t.length;i++){
if(t.head[i] == elem){
return i+1;
}
}
return -1;
}
/**
* @brief modify target element in sequence table
*
* @param t target sequence table
* @param elem old element
* @param newElem new element
* @return SequenceTable
*/
SequenceTable amendTable(SequenceTable t, int elem, int newElem){
int add = selectTable(t, elem);
t.head[add - 1] = newElem;
return t;
}
/**
* @brief show sequence table
*
* @param 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;
}
C语言数据结构学习——顺序表
最新推荐文章于 2024-07-19 23:15:41 发布