Linear table sequence realization (Yan Weimin version)

Linear table order realization

Sequential storage structure type definition

#define Status bool
#define MAXSIZE 100
#define ElemType char
typedef struct
{
    
    
	ElemType *elem;
	int length;
}SqList;

Realization of basic operations

initialization
/*
首先分配空间
再检验空间是否分配成功,不成功就退出
返回假
若分配成功,就将L.length置为零
返回真
*/
Status InitSqlist(SqList& L)
{
    
    
	L.elem = new Elemtype[MAXSIZE];
	if(!L.elem)
	{
    
    
		cout<<"空间分配失败"<<endl;
		return false;
	}
	L.length = 0;
	return true;
}
Value operation
Status GetElem(SqList L, int i, ElemType& e)
{
    
    
	if (i < 1 || i >L.length)
		return false;
	e = L.elem[i - 1];//逻辑上L.elem[0]是第一个,所以i要减一;
	return true;
}
Find
int LocateElem(SqList L, ElemType e)
{
    
    
//在顺序表中查找值为e的数据元素,返回序号
	for(int i = 0; i < L.length; i++)
	{
    
    
		if(L.elem[i] == e)
			return i + 1;
	}
	return 0;
}
insert
Status ListInsert(SqList& L, int i, ElemType e)
{
    
    
	if(i < 1||(i > L.length + 1))
	//为什么是1 < i < L.length+1?
	//因为这个参数i传递的是数学上的第几个
	//而数组的下标是从零开始的,所以前后均应该加1
	{
    
    
		cout<<"数目格式不合理"<<endl;
		return false;
	}
	if(L.length == MAXSIZE)
	{
    
    
		cout<<"数目大小不合理"<<endl;
		return false;
	}
	for(int j = L.length - 1;j >= i-1;j--)
	//为什么j = L.length - 1
	//因为下标从零开始
	//而L.length是从1开始的
	{
    
    
		L.elem[j + 1] = L.elem[j];
	}
	L.elem[i - 1] = e;
	L.length++;
	return true;
}
delete
Status ListDelete(SqList& L, int i)
{
    
    
	if(i < 1||(i > L.length + 1))
	//为什么是1 < i < L.length+1?
	//因为这个参数i传递的是数学上的第几个
	//而数组的下标是从零开始的,所以前后均应该加1
	{
    
    
		cout<<"数目格式不合理"<<endl;
		return false;
	}
	for(int j = i; j <= L.length - 1;j++)
	{
    
    
		L.elem[j - 1] = L.elem[j];
	}
	L.length--;
	return true;
}

Guess you like

Origin blog.csdn.net/Stanford_sun/article/details/114368484