数据结构 / 顺序表操作 / 顺序表尾部添加

顺序表尾部添加函数代码

/*
 *注意要判断顺序表是否已满
 *成功返回0
 *失败返回-1
 * */

int append(sqlist *list, data_type element)
{
	if(NULL==list || 1==is_list_full(list))
	{
		return -1;
	}

	list->arr[list->len++]=element;
	return 0;
}

完整代码

#include 
#include 
#include 

#define MAXSIZE 20
typedef int data_type;

typedef struct SQLIST
{
	//数据元素
	data_type arr[MAXSIZE];
	int len;
	

}sqlist;

sqlist *create();
int append(sqlist *list, data_type element);
int is_list_full(sqlist *list);
void output(sqlist *list);

int main(int argc, const char *argv[])
{
	
	data_type element;
	int n;

	puts("> ---create a sqlist---\n");
	sqlist *list=create();
	if(NULL==list)
	{
		printf("failed to create sqlist!\n");
		return -1;
	}
	
	printf("a sqlist has been created!\n");
	putchar(10);

	
	puts("> ---append elements to list---\n");
	printf("how many element do you want to append?(max:%d):", MAXSIZE);
	scanf("%d", &n);
	for(int i=0; ilen=0; 	
	
	//顺序表数据元素清零
	memset(list->arr, 0, sizeof(list->arr));
	return list;
}

/*
 *满了返回1
 *不满返回0
 * */

int is_list_full(sqlist *list)
{
	return list->len==MAXSIZE ? 1 : 0;
}

/*
 *注意要判断顺序表是否已满
 *成功返回0
 *失败返回-1
 * */

int append(sqlist *list, data_type element)
{
	if(NULL==list || 1==is_list_full(list))
	{
		return -1;
	}

	list->arr[list->len++]=element;
	return 0;
}

/*
 *
 *
 * */

void output(sqlist *list)
{
	if(NULL==list)
	{
		printf("list is NULL!\n");
	}

	for(int i=0; ilen; i++)
	{
		printf("%d\t", list->arr[i]);
	}
	putchar(10);

}

目录 / 学习笔记快速链接

你可能感兴趣的:(数据结构,c语言,linux)