线性表的初始化,增删查操作等

线性表的初始化,增删查操作等

#include<stdio.h>
#define LISTSIZE 100
typedef int DataType;

typedef struct{
	DataType items[LISTSIZE];
	int length;
}SqList; 


// 2-1 init list

int InitList(SqList *L){
	L->length = 0;
	return 1;
}

// 2-2 length
int ListLength(SqList L){
	return L.length;
}

// 2-3 empty
int ListEmpty(SqList L){
	if(L.length <= 0) return 1;
	else return 0;
}

// 2-4 insert

int ListInsert(SqList *L,int pos,DataType item){
	int i;
	if(L->length >= LISTSIZE){
		printf("it had full,you can insert it\n");
		return 0;
	}

	if(pos<=0 || pos>L->length+1){
		printf("you choose position is nosuitbale,please choose the [1,length+1]\n");
		return 0;
	}

	for(i = L->length -1;i>=pos-1;i--){
		L->items[i+1] = L->items[i];
	}

	L->items[pos-1] = item;
	L->length++;
	return 1;
}


// 2-5 delete
int ListDelete(SqList *L,int pos,DataType *item){
	int i;
	if(ListEmpty(*L)){
		printf("this is a empty List\n");
		return 0;
	}

	if(pos<1||pos>L->length){
		printf("delete the position is nosuitbale,the range is [1,length]\n");
		return 0;
	}

	*item = L->items[pos-1];
	for (int i = 0; i < L->length; ++i)
	{
		L->items[i-1] = L->items[i];
		/* code */
	}
	L->length --;
	return 1;
}


// 2-6 find

int Find(SqList L,DataType item){
	int pos =0;
	if(ListEmpty(L)){
		printf("this is a empty List\n");
		return 0;
	}

	while(pos<L.length && L.items[pos]!=item){
		pos++;
	}

	if(pos<L.length) return pos+1;
	else return 0;
}

// 2-7 get element

int GetElem(SqList L,int pos,DataType *item){
	if(ListEmpty(L)) return 0;

	if(pos<0 || pos>L.length){
		printf("please input again!\n");
		return 0;
	}

	*item = L.items[pos-1];
	return 1;
}


// 2-8 TraverseList

int TraverseList(SqList L){
	int i;
	for(i = 0 ; i <L.length;i++){
		printf("%d\t",L.items[i] );
	}
	printf("\n");
	return 0;
}


int main(){

	int i;
	int data[7] = {0,1,1,2,3,5,8};
	DataType item;
	SqList fibo;
	printf("init list\n");
	InitList(&fibo);

	for(i = 0; i < 7;i++){
		if(!ListInsert(&fibo,i+1,data[i])){
			printf("run wrong\n");
			return 0;
		}
	}

	printf("\nbefore delete \n");
	TraverseList(fibo);

	if(!ListDelete(&fibo,7,&item)){
		printf("run wrong\n");
		return 0;
	}



	printf("\nafter delete \n");
	TraverseList(fibo);
	return 1;

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值