(数据结构)(C++)顺序表的建立和部分基本操作

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
 
using namespace std;
 
#define  ElemType int

#define MAXSIZE 100
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2

typedef struct{       //结构体 
	int data[MAXSIZE];
	int length;
}Sqlist,*SqList;
 
//建立顺序表 
void CreateList(SqList &L){ 
	L= new Sqlist;
	cout<<"请输入建立顺序表的长度:";
	int len; 
	cin>>len; 
	int i=0;
	while(i<len){
     cout<<"请输入第"<<i+1<<"个元素:"; 
     ElemType elem;
	 cin>>elem;
	 L->data[i]=elem;
     i++;
	}
	L->length=i;//此长度为物理长度 
}
 
//初始化线性表 
void InitList(SqList &L){
	L=new Sqlist;
	L->length=0;
} 
 
//销毁线性表 
void DestroyList(SqList &L){
	delete(L);
}
  
//判断是否为空表 
bool ListEmpty(SqList L){
	return(L->length==0); 
}
 
//输出线性表
void PrintList(SqList L){
	int i;
	cout<<"输出 "; 
	for(i=0;i<L->length;i++){
		cout<<L->data[i]<<" "; 
	}
} 
 
//求线性表长度
int ListLength(SqList L){
	return(L->length);
} 
 
//求线性表中某个数据的逻辑位置 
int GetElemLocation(SqList L){ 
    cout<<"请输入你要查找的元素:";
    ElemType elem;
	int i=0;
	while(i<=L->length-1&&L->data[i]!=elem){
		i++;
	}
	if(i>L->length-1){
		return -1;
	}else{
		return i+1;//转换为逻辑位置 
	}
} 
 
 
//按根据位置查找元素 
ElemType GetElem(SqList L){
	cout<<"请输入你元素位置:";
	int location;
	cin>>location;
	location=location-1;
	return L->data[location];
}
 
//插入数据元素
bool InsertList(SqList &L){
	cout<<"请输入你要插入的位置:";
	int location;
	cin>>location;
	location--;//转化为物理位置 
	if(location<0||location>L->length-1||L->length>=MAXSIZE-1){
	return false;
	}
	int i; 
	for(i=L->length;i>location;i--){
		L->data[i]=L->data[i-1];
		}
		cout<<"请输入你要插入的元素:";
		ElemType elem;
		cin>>elem; 
		L->data[i]=elem;
		L->length++;
		return true; 
} 
 
 
//删除指定位置数据元素
bool DeleteList(SqList &L){
	cout<<"请输入你要删除的位置:";
	int location;
	cin>>location; 
	if(location<1||location>L->length){
		return false;
	}
	location--;//将顺序表逻辑序号转化成物理序号 
	for(int j=location;j<L->length-1;j++){
		L->data[j]=L->data[j+1];
	}
	L->length--;
	return true;
}
 
 
//主函数 
int main(){
	SqList L;
	InitList(L);
	CreateList(L);
	cout<<endl;
	
	PrintList(L);
	cout<<endl; 
	
	int length = ListLength(L);
	cout<<"长度为:"<<length;
	cout<<endl;
	
	InsertList(L);
	PrintList(L);
	cout<<endl;
	 
	DeleteList(L);
	PrintList(L);
	cout<<endl; 
	//其他操作可以自己试一试 
	return 0; 
} 

8d25d410dc5c48179766d26a8e0e5f3e.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值