天天看点

线性表之顺序表的实现

#include <iostream>
using namespace std;

// 顺序表的结构体
#define MAXSIZE 50

// 数据元素结构体
typedef struct 
{
	int x;
}ElemType;
 
// 静态顺序表 
typedef struct 
{
	ElemType data[MAXSIZE];//数据 
	int length;//数据大小 
}SqList; 

class MySqList{
public:
	MySqList(){
		l.length=0;
		cout<<"初始化完成"<<endl;
	}
	void Travel();//遍历顺序表
	bool ListInert(int loc,ElemType e);//插入数据 
	bool ListDelete(int loc,ElemType &e);//删除数据 
	int LocateElem(ElemType e);//确定元素位置 
	void chice();//功能选择 
private:
	SqList l;
};

//遍历顺序表
void MySqList::Travel(){
	for(int i=0;i<l.length;i++){
		cout<<l.data[i].x<<" ";
	}
	cout<<endl<<"=========================="<<endl;
} 

// 插入数据 
bool MySqList::ListInert(int loc,ElemType e){
	//判断插入位置是否错误
	if(loc<0||loc>l.length+1){
		return false;
	} 
	//判断顺序表是否满
	if(l.length>=MAXSIZE){
		return false;
	} 
	//可以插入右移 
	for(int i=l.length;i>=loc;i--){
		l.data[i]=l.data[i-1];
	} 
	//插入 
	l.data[loc-1]=e;
	l.length++;
	return true;
}

// 删除数据 
bool MySqList::ListDelete(int loc,ElemType &e){
	//判断删除位置是否错误
	if(loc<1||loc>l.length){
		return false;
	} 
	//删除数据的值
	e=l.data[loc-1];
	//左移
	for(int i=loc-1;i<l.length-1;i++){
		l.data[i]=l.data[i+1];
	} 
	l.length--;
	return true;
}  

//确定元素位置
int MySqList::LocateElem(ElemType e){
	for(int i=0;i<l.length;i++){
		if(l.data[i].x==e.x){
			return i+1;
		}
	}
	return 0;
}
//功能选择
void MySqList::chice(){
	while(true){
		cout<<"0-----退出"<<endl;
		cout<<"1-----遍历"<<endl;
		cout<<"2-----插入"<<endl;
		cout<<"3-----删除"<<endl;
		cout<<"4-----确定元素位置"<<endl;
		cout<<"请输入功能选择"<<endl;
		int c;
		cin>>c; 
		int loc;
		ElemType e;
		switch(c){
			case 0:
				cout<<"退出程序"<<endl;
				return;
			case 1:
				Travel();
				break;
			case 2:
				cout<<"请输入插入位置"<<endl;
				cin>>loc;
				cout<<"请输入数据"<<endl;
				cin>>e.x;
				ListInert(loc,e);
				break; 
			case 3:
				cout<<"请输入删除位置"<<endl;
				cin>>loc;
				cout<<"删除元素为"<<endl;
				ListDelete(loc,e);
				cout<<e.x;
				break;
            case 4:
            	cout<<"请输入元素"<<endl;
            	cin>>e.x;
            	cout<<"元素位置为"<<LocateElem(e)<<endl;
            	break;
            default:
            	cout<<"输入格式不正确"<<endl;
            	break;
		}
	}
	
}
int main()
{
	MySqList l;
	l.chice();
	return 0;
} 
           
c++

继续阅读