先上完整代码供码友观看。
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 205;
typedef int ElemType;
class SqList{
private:
ElemType data[maxn];
int Length;
public:
SqList():Length(0) {}
int showLength() {
return Length;
}
void input(int n);//向表中读入n个元素。
void output();
bool GetElem(int i,ElemType *e);
bool ListInsert(int i,ElemType e);
bool ListDelete(int i,ElemType *e);
};
//获取元素操作
bool SqList::GetElem(int i,ElemType *e){
if(showLength()==0||i<1||i>showLength()){
return false;
}
*e=data[i-1];//返回值表示取元素的状态,所取的元素的值存储在指针中。
return true;
}
//在线性表中第i个位置插入元素
bool SqList::ListInsert(int i,ElemType e){
int k;
if(showLength()==maxn) return false;
if(i>showLength()+1||i<1) return false;
if(i<=showLength()){
//所插入的元素不在表尾
for(k=showLength()-1;k>=i-1;k--) {
data[k+1]=data[k];
}
}
data[i-1]=e;
Length++;
return true;
}
//在线性表中第i个位置删除该元素
bool SqList::ListDelete(int i,ElemType *e){
int k;
if(showLength()==0) return false;
if(i<1||i>showLength()) return false;
*e=data[i-1];
if(i<showLength()){
//如果所删除的元素不在表尾,需把被删除之后的元素前移。
for(k=i;k<showLength();k++){
data[k-1]=data[k];
}
}
Length--;
return true;
}
void SqList::input(int n){
for(int i=0;i<n;i++){
cin>>data[i];
}
Length = n ;
}
void SqList::output(){
for(int i=0;i<Length;i++){
cout<<data[i]<<' ';
}
}
int main()
{
int n,element;
cin>>n;
SqList Sq;
Sq.input(n);
//取第五个元素作测试
Sq.GetElem(5,&element);
cout<<element<<endl;
//在位置5插入元素
Sq.ListInsert(5,25);
Sq.output();cout<<endl;
cout<<"Length:"<<Sq.showLength();
cout<<endl;
//在位置4删除元素
Sq.ListDelete(4,&element);
cout<<element<<endl;
Sq.output();cout<<endl;
cout<<"Length:"<<Sq.showLength();
cout<<endl;
cout<<"Bye~";
return 0;
}
代码的细节不做展开讲解,学过C++的朋友一眼就能看懂。刚放暑假,开始自学数据结构,线性表使数据结构的入门,而其顺序存储结构是最简单易懂的。
顺序存储结构的优点:①无需为表示表中元素的逻辑关系而额外增加存储空间。
②可以快速地存取表中任意位置的元素。
缺点:①插入和删除操作需要移动大量元素。(因此其链式存储结构用指针实现)
②当线性表的长度变化较大时,难以确定存储空间的容量。(因此链式存储结构使用动态建立内存的方式实现)
③造成存储空间的“碎片”。(此处不太懂,但总的来说个人认为其链式存储结构优于顺序存储结构,链式存储结构将于稍后奉上。)
1097




被折叠的 条评论
为什么被折叠?



