顺序表简介
顺序表就是一片连续存储的线性表。
优点:查询方便、修改便捷(直接根据下标进行查询修改)
缺点:大小限定;插入、删除会移动大量数据
声明顺序表
#define SIZE 100
typedef int data_t;
typedef struct list{
data_t data[SIZE]; //保存元素
int last; //保存元素下标
}seqlist;
创建顺序表并初始化
seqlist* create_seqlist()
{
seqlist *head = (seqlist*)malloc(sizeof(seqlist)); //创建表头
//判断是否创建成功
if(NULL == head)
return NULL;
memset(head->data,0,sizeof(head->data)); //清空表数据
head->last = -1; //初始化表,并表示为空
return head;
}
求表长
int get_len_seqlist(seqlist* head)
{
//判断head传递是否成功
if (NULL == head)
{
return -1;
}
return head->last+1;
}
判断表是否为空
int empty_seqlist(seqlist* head)
{
if (NULL == head)
{
return -1;
}
return ((head->last) < 0:1?0)
}
判断表是否为满
int full_seqlist(seqlist* head)
{
if (NULL == head)
{
return -1;
}
return (((head->last+1) == SIZE):1?0)
}
按位置插入
int inset_by_seqlist(seqlist* head, int pos,data_t value)
{
if(NULL == head) perror("inser_by_seqlist");
if(full_seqlist(head) == 1) return-1; //判断是否为空
if(pos < 0||pos > head->last+1) return -1;
//挪位置
int i;
for(i = head->last+1;i>pos;i--)
{
head->data[i] = head->data[i-1];
}
//插入数据
head->data[pos] = value;
head->last++;
return 0;
}
按位置删除
int delete_by_pos_seqlist(seqlist* head,int pos)
{
if (NULL == head) return -1;
if (empty_seqlist(head) == 1) return -1;
if (pos<0||pos>head->last) return -1;
int i;
for(i=pos;i<head->last;i++)
{
head->data[i] = head->data[i+1];
}
head->last--;
return 0;
}
按位置修改
int change_by_pos_seqlist(seqlist *head,int pos,data_t new_value)
{
if (NULL == head) return -1;
if (empty_seqlist(head) == 1) return -1;
if (pos<0||pos>head->last) return -1;
head->data[pos] = new_value;
return 0;
}
按位置查询
data_t find_by_pos_seqlist(seqlist *head,int pos)
{
if (NULL == head) return -1;
if (empty_seqlist(head) == 1) return -1;
if (pos<0||pos>head->last) return -1;
return head->data[pos];
}
以上就是顺序表按位置的增删改查,而顺序表按数值的增删改查就是基于按位的增删改查,如下所示:
按数值查找
int find_by_value_seqlist(seqlist *head,data_t value)
{
if (NULL == head) return -1;
if (empty_seqlist(head) == 1) return -1;
int i;
for (i=0;i<=head->last;i++)
{
if(head->data[i] == value)
return i;
}
return -1;
}
按数值插入/按数值修改
其实按数值插入就是按数值修改
int change_by_value_seqlist(seqlist *head,data_t old_value,data_t new_value)
{
if (NULL == head) return -1;
if (empty_seqlist(head) == 1) return -1;
int pos = find_by_value_seqlist(head,new_value);
change_by_pos_seqlist(head,pos,new_value);
}
按数值删除
int delete_by_value_seqlist(seqlist *head,data_t value)
{
if (NULL == head) return -1;
if (empty_seqlist(head) == 1) return -1;
int pos = find_by_value_seqlist(head,value);
delete_by_pos_seqlist(head,pos);
}
打印顺序表
viod show_seqlist(seqlist *head)
{
int i;
for(i=0;i<=head->last;i++)
printf("%-3d",head->data[i]);
printf("\n");
}
清空顺序表
void clear_seqlist(seqlist *head)
{
if (NULL == head) return ;
head->last = -1;
}
销毁顺序表
注意:这里使用了二级指针;因为head指针里面存放的是顺序表的地址,要取到head指针的内容才能释放掉,所以需要二级指针。
void destory_seqlist(seqlist **head)
{
free(*head);
*head = NULL;
}