顺序表尾部添加函数代码

/*
 *注意要判断顺序表是否已满
 *成功返回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 <string.h&gt;
#include <stdlib.h&gt;
#include <stdio.h>

#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", &amp;n);
	for(int i=0; i<n; i++)
	{
		printf("please input No.%d element:", i+1);
		scanf("%d", &amp;element);
		int ret=append(list, element);
		if(0==ret)
		{
			printf("element has been appended to list!n");
		}
		else
		{
			printf("failed to append element!n");
			break;
		}
	}
	output(list);




	
	return 0;
}



/*
 *申请成功返回堆区内存地址
 *失败返回NULL
 * */

sqlist *create()
{
	sqlist* list=(sqlist*)malloc(sizeof(sqlist));
	if(NULL==list)
	{
		return NULL;
	}
	
	//顺序表长度清零
	list->len=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; i<list->len; i++)
	{
		printf("%dt", list->arr[i]);
	}
	putchar(10);

}

目录 / 学习笔记快速链接

原文地址:https://blog.csdn.net/K_A_Wang/article/details/134631311

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_15089.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注