直接上代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 5
typedef struct Table
{
int *head;
int length;//顺序表实际使用长度
int size; //顺序表分配的存储容量大小
}table;
table t;//全局的
table *initTable ()
{
t.head = (int *)malloc(SIZE*sizeof(int));
if (!t.head)
{
printf("malloc error\n");
free(t.head);
exit(-1);
}
t.length = 0;
t.size = SIZE;
return &t;
}
//首次填充顺序表
void firstaddTable (table *t1)
{
for (int i = 1; i <= t1->size; i++)
{
t1->head[i-1] = i;
t1->length++;
}
if (t1->length > t1->size)
{
printf("length > size\n");
exit(-1);
}
}
void displayTable (table *t1)
{
for (int j = 0; j < t1->length; j++)
{
printf("head[%d] = %d\n", j, t1->head[j]);
}
}
table *delTable(table *t1, int pos)
{
//判断删除位置是否合法
if (pos < 1 || pos > t1->length)
{
printf("删除元素位置不合法\n");
return t1;
}
//delete one element
for (int i = pos; i < t1->length; i++)
{
t1->head[i-1] = t1->head[i];
}
t1->length -= 1;
printf("删除一个元素后:length = %d\n", t1->length);
return t1;
}
table *addTable(table *t1, int elem, int pos)
{
//判断插入位置是否合法
if ((pos < 1) || (pos > (t1->length+1)))
{
printf("插入元素位置不合法\n");
return t1;
}
//顺序表实际使用长度 >= 分配的存储容量
else
if (t1->length >= t1->size)
{
t1->head = (int *)realloc(t1->head, (t1->size+1)*sizeof(int));
if (!t1->head)
{
printf("realloc error\n");
free(t1->head);
}
else
{
t1->size += 1;
}
}
//move
for (int i = t1->length-1; i >= pos-1 ;i--)
{
t1->head[i + 1] = t1->head[i];
}
//add one element
t1->head[pos - 1] = elem;
t1->length += 1;
printf("插入一个元素后:length = %d\n", t1->length);
return t1;
}
//find the location of element
int selectTable(table *t1, int elem)
{
for (int j = 0; j < t1->length; j++)
{
if (elem == t1->head[j])
{
return (j + 1);
}
}
//顺序表中都没有
return -1;
}
//change element
table *amendTable(table *t1, int oldelem, int newelem)
{
int temp_locat = selectTable(t1, oldelem);
t1->head[temp_locat - 1] = newelem;
return t1;
}
int main (void)
{
int location = 0;
table *t1 = initTable();
firstaddTable(t1);
printf("原顺序表:\n");
displayTable(t1);
printf("删除顺序表第二个元素\n");
t1 = delTable(t1, 2);
printf("删除元素后的顺序表:\n");
displayTable(t1);
printf("顺序表第2个元素位置插入元素6:\n");
t1 = addTable(t1, 6, 2);
printf("插入元素后的顺序表:\n");
displayTable(t1);
printf("查找元素3的位置:\n");
location = selectTable(t1, 3);
printf("查找元素在顺序表中的位置为:%d\n", location);
printf("修改元素6为9:\n");
t1 = amendTable(t1, 6, 9);
printf("修改元素后的顺序表:\n");
displayTable(t1);
return 0;
}
日志表现
原顺序表:
head[0] = 1
head[1] = 2
head[2] = 3
head[3] = 4
head[4] = 5
删除顺序表第二个元素
删除一个元素后:length = 4
删除元素后的顺序表:
head[0] = 1
head[1] = 3
head[2] = 4
head[3] = 5
顺序表第2个元素位置插入元素6:
插入一个元素后:length = 5
插入元素后的顺序表:
head[0] = 1
head[1] = 6
head[2] = 3
head[3] = 4
head[4] = 5
查找元素3的位置:
查找元素在顺序表中的位置为:3
修改元素6为9:
修改元素后的顺序表:
head[0] = 1
head[1] = 9
head[2] = 3
head[3] = 4
head[4] = 5