线性表:顺序表实现

在此记录,方便以后学习回顾

#include<cstdio>
#include<iostream>
using namespace std;

#define MaxSize 100
typedef int ElemType;
typedef struct{
	ElemType data[MaxSize];
	int length;
}SqList;
/*
#define InitSize 100
typedef struct{
	ElemType *data;
	int MaxSize,Length;
}SeqList;
SeqList seq=new ELemType[InitSize];
*/
bool InitList(SqList &L);//init 		1
bool Length(SqList L);//return length 		2
bool LocateElem(SqList L,ElemType e);//		3
ElemType GetElem(SqList L,int i);//		4
bool ListInsert(SqList &L,int i,ElemType e);//	5
bool ListDelete(SqList &L,int i,ElemType &e);//	6
bool PrintList(SqList L);//			7
bool Empty(SqList L);	//			8
bool DestroyList(SqList &L);//			9
bool merge(SqList A,SqList B,SqList &C);//	10

bool InitList(SqList &L){
	L.length=0;
	return true;
}
bool Length(SqList L){
	return L.length;
}
bool LocateElem(SqList L,ElemType e){
	for (int i = 0; i < L.length; ++i){
		if (L.data[i]==e){
			return i+1;
		}
	}
	return false;
}
ElemType GetElem(SqList L,int i){
	if (i<1||i>L.length){
		return false;
	}
	if (L.length==0)
	{
		return false;
	}
	return L.data[i-1];
}

bool ListInsert(SqList &L,int i,ElemType e){
	if (i<1||i>L.length+1){
		return false;
	}
	if (L.length>=MaxSize){
		return false;
	}
	for (int j = L.length; j >=i ; --j){
		L.data[j]=L.data[j-1];	
	}
	L.data[i-1]=e;
	L.length++;
	return true;
}
bool ListDelete(SqList &L,int i,ElemType &e){
	if (i<1||i>L.length){
		return false;
	}
	e=L.data[i-1];
	for (int j = i; j < L.length; ++j){
		L.data[j-1]=L.data[j];
	}
	L.length--;
	return true;
}
bool PrintList(SqList L){
	for (int i = 0; i < L.length; ++i){
		printf("%d\n",L.data[i]);
	}
}
bool Empty(SqList L){
	if (L.length==0){
		return true;
	}else{
		return false;
	}
}
bool DestroyList(SqList &L){
	L.length=0;
}
bool merge(SqList A,SqList B,SqList &C){
	int i=0,j=0,k=0;
	if (A.length==0&&B.length==0){
		return false;
	}

	while(i<A.length&&j<B.length){
		if(A.data[i]<B.data[j])
			C.data[k++]=A.data[i++];
		else
			C.data[k++]=B.data[j++];
	}
	while(i<A.length)
		C.data[k++]=A.data[i++];
	while(j<B.length)
		C.data[k++]=A.data[j++];
	C.length=A.length+B.length;
	return true;
}
int main(){
	int x;
	SqList L;
	InitList(L);
	for (int i = 1; i <= 10; ++i)
	{
		cin>>x;
		ListInsert(L,i,x);
	}
	ListDelete(L,4,x);
	cout<<x<<endl;
	cout<<Empty(L)<<endl;
	PrintList(L);
	cout<<LocateElem(L,6)<<endl;
	cout<<GetElem(L,1)<<endl;
	return 0;
}

按照《王道2015数据结构》和《数据结构与算法》王曙燕版。全部实现顺序表操作

1.逻辑从1开始,存储从0开始

2.插入操作注意1<=i<=length+1。判断length<=MaxSize,最后length--;

3.删除1<=i<=length,e的引用返回删除的值,length--;

4.按值查找,返回存储下标+1,返回逻辑下标。return i+1;





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值