线性表-顺序存储结构的C语言实现

#include <stdio.h>
#include <stdlib.h>

#define INIT_SIZE 10
#define ERROR -1
#define OK 1

typedef int ElemType;
typedef bool Status;
typedef Status (*CALL_FN)(ElemType);

typedef struct  list
{
	ElemType* elem;
	ElemType size;
	ElemType length;
}List;

void InitList(List* L)
{
	L->elem = (ElemType*)malloc(INIT_SIZE*sizeof(ElemType));
	if (!L->elem)
		printf("failed to initialize the list");
	L->size = INIT_SIZE;
	L->length = 0;
}

ElemType getListLength(List L)
{
	return L.length;
}

Status ListEmpty(List L)
{
	if(L.length == 0)
		return true;
	else
		return false;
}

Status ClearList(List *L)
{
	free(L->elem);
}


Status getItem(List L, int i, ElemType* e)
{
	if(i <0 || i>L.length-1)
		return ERROR;
	if(ListEmpty(L))
		return ERROR;
	*e = L.elem[i];
	return OK;
}

Status InsertList(List *L, int i, ElemType e)
{
	L->elem = (ElemType*)realloc(L->elem, (L->length+1)*sizeof(ElemType));
	if (!L->elem)
		return ERROR;
	for(int j = i; j<=L->length-1; j++)
	{
		*(L+j+1) = *(L+j);
	}
	(*L).elem[i] = e;
	//*(L+i) = e;
	L->size = L->size +1;
	L->length = L->length +1;
	return OK;
}


Status DeleteList(List* L, int i, ElemType* e)
{
	for(int j = i; j<=L->length-2; j++)
		*(L+j) = *(L+j+1);
	L->length = L->length-1;
	return OK;
}

Status TraverseList(List L, CALL_FN visit)
{
	for(int i =0; i<=L.length-1; i++)
		visit(i);
	return OK;
}

Status display(List L)
{
	for (int i =0; i<=L.length-1; i++)
		printf("%d ", L.elem[i]);
	printf("\n");
}


Status visit(ElemType i)
{
	printf("%d visited.\n", i);
}


int main()
{
	List A;
	List * p;
	p = &A;
	InitList(p);
	display(A);

	InsertList(p, 0, 1);
	InsertList(p, 1, 2);
	InsertList(p, 2, 3);
	InsertList(p, 3,4);
	display(A);

	int e;
	int* p_e = &e;
	getItem(A, 2, p_e);
	printf("p_e is:%d\n", *p_e);

	TraverseList(A, visit);

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值