#include <stdio.h>
#include <stdlib.h>
#if 0
void *malloc(size_t size);
功能:在堆区开辟空间
参数:size开辟空间的大小
返回:返回堆区的首地址,需要强制类型转换
#endif
#define N 10
typedef int data_t;
typedef struct {
data_t a[N];
int last;
}sqlist_t;
sqlist_t *sqlist_create()
{
sqlist_t *p = NULL;
p = (sqlist_t *)malloc(sizeof(sqlist_t));
if(p == NULL)
return NULL;
p->last = -1;
return p;
}
int sqlist_is_full(sqlist_t *p)
{
if(p != NULL)
return p->last == N-1 ? 1 : 0;
#if 0
if(p->last == N-1)
{
return 1;
}
else
{
return 0;
}
#endif
}
int sqlist_is_empty(sqlist_t *p)
{
if(p != NULL)
return p->last == -1 ? 1 : 0;
}
int sqlist_insert(sqlist_t *p, data_t value)
{
if(p == NULL)
return -1;
if(sqlist_is_full(p))
{
printf("full\n");
return -1;
}
p->last++;
p->a[p->last] = value;
return 0;
}
int sqlist_delete(sqlist_t *p)
{
if(p == NULL)
return -1;
if(sqlist_is_empty(p))
{
printf("empty\n");
return -1;
}
p->last--;
return 0;
}
int sqlist_change(sqlist_t *p, data_t old, data_t new)
{
int i;
if(p == NULL)
return -1;
for(i=0; i<=p->last; i++)
{
if(p->a[i] == old)
{
p->a[i] = new;
}
}
return 0;
}
int sqlist_insert_pos(sqlist_t *p, int pos, data_t value)
{
if(p == NULL)
return -1;
if(sqlist_is_full(p))
{
printf("full\n");
return -1;
}
if(pos < 0 || p->last + 1 < pos)
{
printf("pos error\n");
return -1;
}
int i;
for(i=p->last; i>= pos; i--)
{
p->a[i+1] = p->a[i];
}
p->a[pos] = value;
p->last++;
return 0;
}
int sqlist_delete_pos(sqlist_t *p, int pos)
{
if(p == NULL)
return -1;
if(sqlist_is_empty(p))
{
printf("empty\n");
return -1;
}
if(pos < 0 || p->last < pos)
{
printf("pos error\n");
return -1;
}
int i;
for(i=pos+1; i<=p->last; i++)
{
p->a[i-1] = p->a[i];
}
p->last--;
return 0;
}
int sqlist_delete_repeat(sqlist_t *p)
{
int i,j;
if(p == NULL)
return -1;
for(i=0; i<p->last; i++)
{
for(j=i+1; j<=p->last; j++)
{
if(p->a[i] == p->a[j])
{
sqlist_delete_pos(p,j);
j--;
}
}
}
return 0;
}
int sqlist_show(sqlist_t *p)
{
int i;
if(p == NULL)
return -1;
for(i=0; i<=p->last; i++)
{
printf("%d ",p->a[i]);
}
putchar('\n');
}
int main(int argc, const char *argv[])
{
sqlist_t *l = sqlist_create();
if(l == NULL)
return -1;
sqlist_insert(l,10);
sqlist_insert(l,20);
sqlist_insert(l,30);
sqlist_insert(l,40);
sqlist_insert(l,50);
printf("insert data:");
sqlist_show(l);
sqlist_delete(l);
printf("delete data:");
sqlist_show(l);
sqlist_change(l,20,12);
printf("change data:");
sqlist_show(l);
sqlist_insert_pos(l, 3, 15);
printf("insert pos:");
sqlist_show(l);
sqlist_delete_pos(l, 3);
printf("delete pos:");
sqlist_show(l);
free(l);
putchar('\n');
sqlist_t *w = sqlist_create();
sqlist_insert(w,11);
sqlist_insert(w,12);
sqlist_insert(w,13);
sqlist_insert(w,11);
sqlist_insert(w,11);
sqlist_insert(w,15);
sqlist_insert(w,11);
sqlist_insert(w,16);
sqlist_insert(w,17);
printf("insert data:");
sqlist_show(w);
sqlist_delete_repeat(w);
printf("delete repeat:");
sqlist_show(w);
free(w);
return 0;
}
测试结果

任何函数的返回值都需要做判断,提高程序的健壮性!