Linux C 数据结构—线性表
顺序表特点:
优势: 存储密度高,可以随机存取。
缺点:
1) 要求系统可以提供一片连续的存储空间,
2) 会出现成片移动的现象。
3) 数据的个数固定。
#include <stdio.h>
#define MAX 16
typedef int data_t;
typedef struct
{
data_t data[MAX]; //第一个成员: 存放具体的有效数据。
int last; //第二个成员: 存放有效数据的个数。
}seqlist_t;
//创建空顺序表
seqlist_t *creat_empty_sqlist()
{
seqlist_t *p = malloc(sizeof(seqlist_t));
p->last = 0;
return p;
}
//判断顺序表是否为空:是空:返回1,没空,返回0.
int empty_sqlist(seqlist_t *p)
{
if(p->last == 0)
return 1;
else
return 0;
}
//判断表是否满:是满:返回1.没满,返回0
int full_sqlist(seqlist_t *p)
{
if(p->last == MAX)
return 1;
else
return 0;
}
//清空顺序表
void clear_sqlist(seqlist_t *p)
{
p->last = 0;
}
//求表长度。(存放有效数据的个数)
int length_sqlist(seqlist_t *p)
{
return p->last;
}
//在指定位置插入数据。
int insert_sqlist(seqlist_t *L,data_t x,int pos)
{
int i;
if(full_sqlist(L) == 1 || pos > L->last+1 )
{
return -1;
}
for(i=L->last-1; i>=pos-1 ;i--)
{
L->data[i+1] = L->data[i];
}
L->data[pos-1] = x;
L->last++;
return 1;
}
//删除指定位置上的数据。
int delete_sqlist(seqlist_t *L,int pos)
{
int i;
if(empty_sqlist(L) == 1 || pos > L->last)
{
return -1;
}
for(i=pos-1; i<L->last ;i++)
{
L->data[i] = L->data[i+1];
}
L->last--;
return 1;
}
//查找表中是否存在值为 value 的数据。
int search_sqlist(seqlist_t *L,data_t value)
{
int i;
for(i=0; i<L->last; i++)
{
if(value == L->data[i])
{
return i+1;
}
}
return 0;
}
//打印顺序表。
void print_array(seqlist_t *L)
{
int i;
for(i=0; i<L->last; i++)
printf("%5d",L->data[i]);
printf("\n");
return ;
}
//测试以上函数是否好用。
int main()
{
seqlist_t *p = creat_empty_sqlist();
int n = empty_sqlist(p);
insert_sqlist(p,11,1);
insert_sqlist(p,33,2);
insert_sqlist(p,22,2);
insert_sqlist(p,55,4);
print_array(p);
delete_sqlist(p,3);
print_array(p);
if( search_sqlist(p,44) == 0)
printf("not found 44\n");
if(search_sqlist(p,33) == 0)
printf("Not found 33\n");
free(p);
return 0;
}