顺序表几种基础函数的实现

数据结构首先接触的就是顺序表,以下是几种函数的实现:

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

#define LIST_INIT_SIZE 100//线性表储存空间的初始分配量

#define LISTINCREMENT 10//线性表储存空间的分配增量

#define TRUE 1

#define FALSE 0

#define OK 1

#define ERROR 0

#define INFEASIBLE -1

#define OVERFLOW -2

typedef int Status;

typedef struct{
		int *elem;//储存空间基址 
		int length;//当前长度 
		int listsize;//当前分配的储存容量 
	}SqList; 
 
Status Initlist(SqList &L){
	//构造线性表
	L.elem = (int*)malloc(LIST_INIT_SIZE*sizeof(int));
	if(!L.elem) exit(OVERFLOW);//储存分配失败
	L.length = 0;
	L.listsize =  LIST_INIT_SIZE;
	return OK;	
}

Status DestroyList(SqList &L){
	//销毁线性表
	free(L.elem);
    L.elem=NULL;
    L.length=0;
    L.listsize=0;
    return OK;
}

Status ClearList(SqList &L){
	//将L置为空表
	L.length=0;
    return OK; 
}

Status ListEmpty(SqList L){
	//判断线性表是否为空
	if(!L.elem)
	return FALSE;
	else
	return TRUE;
}

Status Listlength(SqList L){
	//计算线性表的长度 
	return L.length;
}

Status GetElem(SqList L,int i,int &e){
	if(i<1||i>L.length){
		return ERROR;
	}
	else{
		return e=L.elem[i-1];
	}
}

Status PriorElem(SqList L,int cur_e,int &pre_e){
	printf("Please enter your number:");
	scanf("%d",&cur_e);
	int i;
	for(i=0;i<L.length;i++){
		if(cur_e==L.elem[0]){
			return FALSE;
			break;
		}
		else if(cur_e==L.elem[i]){
			pre_e=L.elem[i-1];
			break;
		}
	}
	
if(i==L.length){
	return FALSE;
} 
}

Status NextElem(SqList L,int cur_e,int &next_e){
	printf("Please enter your number:");
	scanf("%d",&cur_e);
	int i;
	for(i=0;i<L.length;i++){
		if(cur_e==L.elem[L.length]){
			return FALSE;
			break;
		}
		else if(cur_e==L.elem[i]){
			next_e=L.elem[i+1];
			break;
		}
	}
	
if(i==L.length){
	return FALSE;
} 
}

Status ListInsert(SqList &L,int i,int e){
	printf("Where do you want to insert a number?");
	scanf("%d",&i);
	printf("What number do you want to insert?");
	scanf("%d",&e);
	if(i>0&&i<L.length+2){
		L.length++; 
		if(L.length >= i){
			int m;
			for(m=i;m<L.length;m++){
				L.elem[m+1]=L.elem[m]; 
			}
			L.elem[i-1]=e;
		}
		return OK;
	} 
	else return FALSE;
}

Status ListDelete(SqList L,int i,int &e){
	printf("Where do you want to delete a number?");
	scanf("%d",&i);
	if(i>0&&i<L.length+1){
		e=L.elem[i-1];
		if(L.length > i){
			int m;
			for(m=i-1;m<L.length-1;m++){
				L.elem[m]=L.elem[m+1]; 
			}
			L.length--; 
		}
		return OK;
	} 
	else return FALSE;
}

int main(){
........
}

由于顺序表在计算机的储存单元是连续的,所以对于查找元素来说比较容易实现。
但其储存又受到“连续”的限制(万一计算机中没有合适的连续的内存怎么办?)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值