Java教程

顺序表操作综合

本文主要是介绍顺序表操作综合,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

顺序表操作综合

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef int ElemType;

typedef struct SqList{
	ElemType * base;
	int length;
}SqList;

/*
	线性表的初始化 
*/
void InitList_Sq(SqList * L){
	L->base = (ElemType *)malloc(sizeof(ElemType) * MAXSIZE);
	if(!L->base)exit(-1);
	L->length = 0;
}

/*
	销毁线性表 
*/
void DestroyList(SqList * L){
	free(L->base);
} 
/*
	清空线性表 
*/
void ClearList(SqList * L){
	L->length = 0;
}
/*
	求线性表的长度 
*/
int GetLength(SqList * L){
	return L->length;
}
/*
	判断线性表是否为空 
*/
int IsEmptyList(SqList * L){
	if(L->length){
		return 0;
	}else{
		return 1;
	}
}
/*
	根据位置i获取相应位置数据元素的内容 
*/
int getElem(SqList * L, int i, ElemType * e){
	if(i < 1 || i > L->length) return -1;
	*e = L->base[i - 1];
	return 1;
}

/*
	在顺序表元素的插入
	1.判断插入位置i是否合法
	2.判断顺序表的存储空间是否已满,若已满返回error
	3.将第n至第i位的元素依次向后移动一个位置,空出第i个位置
	4.将要插入的新元素e翻入第i个位置
	5.表长加1,插入成功返回ok 
*/
bool ListInsert_Sq(SqList * L, int i, ElemType e){
	if(i < 1 || i > L->length + 1) return false;
	if(L->length == MAXSIZE)return false;
	int j;
	for(j = L->length - 1; j >= i - 1; j--){
		L->base[j + 1] = L->base[j];
	}
	L->base[i - 1] = e;
	L->length++;
	return true;	
}

/*
	在顺序表元素的删除 
	1.判断插入位置i是否合法(合法值<=i<=n) 
	2.将欲删除的元素保留在e中 
	3.将第i+1至第n位的元素依次向前移动一个位置
	5.表长-1,插入成功返回ok 
*/
bool ListDelete_Sq(SqList * L, int i){
	if(i < 1 || i > L->length) return false;
	int j;
	for(j = i; j <= L->length - 1; j++){
		L->base[j - 1] = L->base[j];
	}
	L->length--;
	return true;
}

/*
	在顺序表中查找与指定值e相同的数据元素的位置
	1.从表的一端开始,逐个进行记录的关键字和给定值的比较。
	找到返回该元素的位置序号,未找到返回0 
*/

int LocateElem(SqList * L, ElemType e){
	int i;
	for(i = 0; i < L->length; i++){
		if(L->base[i] == e){
			return i + 1;
		}
	}
	return 0;
}
/*
	输出用于测试 
*/
void Test(SqList * L){
	int i;
	for(i = 0; i < L->length; i++){
		printf("base[%d] = %d\n", i + 1, L->base[i]);
	}
} 
int main(){
	SqList L;
	InitList_Sq(&L);
	//测试插入 
	int i;
	for(i = 0; i < 20; i++){
		ListInsert_Sq(&L, i+1, i);	
	}
	ListInsert_Sq(&L, 3, 100);
	//测试删除 
	ListDelete_Sq(&L, 3);
	Test(&L);
	return 0;
} 
这篇关于顺序表操作综合的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!