用数组实现的线性表


测试函数:文件名 test_array_list.c

#include<stdio.h>
#include "array_list.h"

int main()
{	
	int value;
	seq_list seq_list_array;
	list_init(&seq_list_array);  //不加这句的话会出现多一个元素的情况,数值是1 

	list_insert_element(&seq_list_array, 1, 5);
	list_insert_element(&seq_list_array, 2, 7);
	list_insert_element(&seq_list_array, 3, 6);
	list_insert_element(&seq_list_array, 2, 10);
	print_list(seq_list_array);
	list_get_element(seq_list_array, 2 ,&value);
	printf("The value is %d\n", value);
	print_list(seq_list_array);
	list_del_element(&seq_list_array, 3, &value);
	printf("The value is %d\n", value);
	print_list(seq_list_array);
}


头文件:文件名 array_list.h

#ifndef _ARRAY_LIST_H
#define _ARRAY_LIST_H

#define ERROR 0
#define OK 1

#define MAX_SIZE 10

typedef int status;
typedef int data_type;

typedef struct
{
	data_type data[MAX_SIZE];
	int length;
}seq_list;

void list_init(seq_list *L);

status list_get_element(seq_list L, int location, data_type *e);

status list_insert_element(seq_list *L, int location, data_type e);

status list_del_element(seq_list *L, int location, data_type *e);

void print_list(seq_list L);

#endif


实现代码:文件名 array_list.c

#include<stdio.h>
#include "array_list.h"

void list_init(seq_list *L)
{
	L->length = 0;
}

status list_get_element(seq_list L, int location, data_type *e)
{
	if(L.length == 0 || location < 1 || location > L.length)
		return ERROR;
	
	*e = L.data[location-1];
	return OK;
}

status list_insert_element(seq_list *L, int location, data_type e)
{
	int k;
	
	if(L->length == MAX_SIZE)
		return ERROR;
	
	if(location < 1 || location > L->length + 1)
		return ERROR;
	
	if(location <= L->length)
	{
		for(k=L->length-1; k>=location-1; k--)
			L->data[k+1] = L->data[k];
	}
	
	L->data[location-1] = e;
	L->length++;
	return OK;
}

status list_del_element(seq_list *L, int location, data_type *e)
{
	int k;
	
	if(L->length == 0)
		return ERROR;
	
	if(location < 1 || location > L->length)
		return ERROR;
	
	*e = L->data[location-1];
	
	if(location < L->length)
	{
		for(k=location; k<L->length; k++)
			L->data[k-1] = L->data[k];
	}
	
	L->length--;
	return OK;
}

void print_list(seq_list L)
{
	int k;
	
	printf("print the whole list\n");
	printf("The length of list is %d\n", L.length);
	
	for(k=0; k<L.length; k++)
		printf("%d\t", L.data[k]);
		
	printf("\n");
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值