#include<iostream>
#include<malloc.h>
using namespace std;
#define Maxsize 50
typedef int ElemType;
typedef struct {
	ElemType data[Maxsize];
	int length;
}sqList;
//函数声明
void CreatList(sqList *&L,ElemType a[],int n);
void disList(sqList *L);
bool ListEmpty(sqList *L);
int ListLength(sqList *L);
bool GetElem(sqList *L,int i,ElemType &e);
int locateElem(sqList *L,ElemType e);

//函数定义
//利用数组创建线性表 
void CreatList(sqList* &L,ElemType a[],int n){
	L = (sqList*)malloc(sizeof(sqList));
	for(int i=0;i<n;i++){
		L->data[i]=a[i];
	}
	L->length=n;
	cout<<"CreatList succ!"<<endl;
}
//输出线性表
void disList(sqList *L){
	if(ListEmpty(L))  return ;
	for(int i=0;i<L->length;i++){
		
		cout<<(L->data[i])<<" ";	 
	}
	cout<<endl;
	cout<<"disList succ!"<<endl;
}
//判断线性表是否为空 
bool ListEmpty(sqList *L){
//	cout<<L->length<<"S";
	if((L->length)==0){
		return true;
	}else{
		return false;
	}
}
//求线性表的长度 length
int ListLength(sqList *L){
	return L->length;
} 
//求某个位置元素的值
bool GetElem(sqList *L,int i,ElemType &e){
	if(i<1||i>L->length)  return false;
	e = L->data[i-1];
	return true;
	
}
//安装元素的值查找位置
int locateElem(sqList *L,ElemType e){
	int i=0;
	while(i<L->length && L->data[i]!=e)  i++;
	if(i>=(L->length)){
		return -1;
	}
	else {
		return (i+1);
	}
} 

int main() {
	sqList *list;
	ElemType arr[7] = {2,4,8,6,1,7,9};
	CreatList(list,arr,7);
	disList(list);
	cout<<"线性表长度:"<<ListLength(list)<<endl;
	
	for(int i=0;i<=(list->length+1);i++){
		int a;
		if(GetElem(list, i, a))  cout<<"找到了第"<<i<<"个元素值为"<<a<<endl;
		else cout<<"找到了第"<<i<<"个元素,越界"<<endl;
	}
	cout<<endl;
	for(int i=0;i<=10;i++){
		int loc;
		if((loc=locateElem(list, i))>0)  cout<<"找到了值为"<<i<<"的元素是第"<<loc<<"个"<<endl;
		else cout<<"值为"<<i<<"的元素没找到"<<endl;
	}	
	return 0;
}

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐