数据结构-实验一

开始学数据结构了,第一次U•ェ•*U

代码

#include<iostream>
using namespace std; 

#define MAXSIZE 100
#define ERROR 0
#define OK 1

typedef char Elemtype;
typedef int Status;

//顺序表的存储结构** 
typedef struct SqList{
	Elemtype *elem;
	int length;
}SqList;
//顺序表的创建
Status InitList(SqList &L){
	L.elem=new Elemtype[MAXSIZE];
	if(!L.elem)return ERROR;
	L.length=0;
	return OK;
}
//顺序表的插入
Status InsertList(SqList &L,int i,Elemtype e){
	if(i<1||i>L.length+1)return ERROR;
	if(L.length == MAXSIZE){
		cout<<"表已满!"<<endl;
		return ERROR;
	}
	for(int j=L.length-1;j>=i-1;j--)
    L.elem[j+1] = L.elem[j];
	L.elem[i-1] = e;
	L.length++;
	return OK;    
} 
// 顺序表的取值
int GetElem(SqList L,int i,Elemtype &e){
	if(L.length ==0 ){
	cout<<"表为空!"<<endl;
		return ERROR;
	}
	if(i<1||i>L.length) return ERROR;
	e = L.elem[i-1];
	return OK;
} 
//顺序表的查找
int LocateElem(SqList L,Elemtype e){
	if(L.length ==0 ){
	cout<<"表为空!"<<endl;
		return ERROR;
	}
	for(int i=0;i<L.length;i++)
	if(L.elem[i]==e) return i+1;
	cout<<"表中没有您查询的字符"<<endl; 
	return 0; 
} 
//顺序表的删除
Status ListDelete(SqList &L,int i,Elemtype &e){
	if(L.length ==0 ){
	cout<<"表为空!"<<endl;
		return ERROR;
	}
	if(i<1||i>L.length) return ERROR;
	e = L.elem[i-1];
	for(int j=i;j<=L.length-1;j++)
	L.elem[j-1]=L.elem[j];
	--L.length;
	return OK; 
}
//顺序表的遍历 
Status TraverseList(SqList L){
    cout<<"表内所有元素:"<< endl;
    for(int i=0;i<L.length;i++){
       cout<<L.elem[i]<<" ";
	}
	cout<<endl;
	return OK;
} 
//顺序表的销毁
Status DestroyList(SqList &L){
	if(L.elem!=NULL)
	{
		delete[] L.elem;
	}
	L.elem=NULL;
	return OK;
}
 
int main(){
	SqList L;
	InitList(L);
	InsertList(L,1,'a');
	InsertList(L,2,'b');
	InsertList(L,3,'c');
	InsertList(L,4,'d');
	InsertList(L,5,'e');
	
    Elemtype num1;
	GetElem(L,1,num1);
	 cout<<"取值为:"<<num1<<endl;
	 
	Elemtype num2;
	 cout<<"请输入您要查询的字符:"<<endl;
	 cin>>num2;
	LocateElem(L,num2);
	 cout<<num2<<"在第"<<LocateElem(L,num2)<<"个位置"<<endl;
	
	Elemtype num3;
	ListDelete(L,3,num3);
	 cout<<"删除元素为:"<<num3<<endl;
	
	TraverseList(L);
	DestroyList(L);
	 cout<<"L已被销毁"<<endl; 
}

一部分运行结果
数据结构-实验一
数据结构-实验一

上一篇:TortoiseSVN文件夹及文件图标不显示的解决办法


下一篇:线性表-SqList(顺序表)