#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<iostream>
#define MaxSize 50
using namespace std;
typedef int ElemType;
typedef struct{
ElemType data[MaxSize];
int length;
}Sqlist;
//建立顺序表
void CreatList(Sqlist *&L,ElemType a[],int n){
int i=0,k=0;
L=(Sqlist *)malloc(sizeof(Sqlist));
while(i<n){
L->data[k]=a[i];
k++;i++;
}
L->length=k;
}
//初始化线性表
void InitList(Sqlist *&L){
L=(Sqlist*)malloc(sizeof(Sqlist));
L->length=0;
}
//销毁线性表
void DestroyList(Sqlist *&L){
free(L);
}
//判断线性表是否为空表
bool ListEmpty(Sqlist *L){
return(L->length==0);
}
//求线性表的长度
int ListLength(Sqlist *L){
return (L->length);
}
//输出线性表
void DispList(Sqlist *L){
int i;
for(i=0;i<L->length;i++)
printf("%d ",L->data[i]);
printf("\n");
}
//按序号求线性表中元素
bool GetElem(Sqlist *L,int i,int &e){
if(i<1||i>L->length)
return false;
e = L->data[i-1]; //为啥用bool而不是int(又可以判断又可以用e返回)
return true;
}
//按元素查找
int LocateList(Sqlist*L,ElemType e){
int i=0;
while(i<L->length&&L->data[i]!=e)
i++;
if(i>=L->length)
return 0;
else return i+1;
}
//插入数据元素
bool ListInsert(Sqlist *&L,int i,ElemType e){
if(i<1||i>L->length+1||i>MaxSize)
return false;
i--;
int j;
for(j=L->length;j>i;j--){
L->data[j]=L->data[j-1];
}
L->data[i]=e;
L->length++;
return true;
}
//删除数据元素
bool ListDelete(Sqlist *&L,int i,ElemType &e){//e的目的是在于告诉你删除的是哪个元素
if(i<1||i>L->length)
return false;
i--;
e=L->data[i];
int j;
for(j=i;j<L->length;j++)
L->data[j]=L->data[j+1];
L->length--;
return true;
}
int main(){
Sqlist *h; Sqlist *L;
InitList(L);
int n = 5,m;
ElemType a[]={1,2,1,4,2};
CreatList(h,a,n);
cout<<"线性表的长度是:"<<ListLength(h)<<endl;
GetElem(h,4,m);
cout<<"所要查找的第i个逻辑序号元素"<<m<<endl;
cout<<"线性表内容:";DispList(h);
cout<<"表中第一个值为4的元素的逻辑序号为:"<<LocateList(h,4)<<endl;
cout<<"线性表L是否为空(空为1,非空为0)"<<ListEmpty(L)<<endl;
cout<<"h是否为空(空为1,非空为0)"<<ListEmpty(h)<<endl;
ListInsert(L,1,7); ListInsert(L,2,9);
cout<<"L目前线性表内容:";DispList(L);
int d=0;
ListDelete(L,1,d);
cout<<"L目前线性表内容:";DispList(L);
cout<<d<<endl;
DestroyList(h);
}
2022/9/11 顺序线性表的基本运算
最新推荐文章于 2023-05-01 18:00:11 发布
本文介绍了C++编程中如何创建、初始化、销毁线性顺序表,并提供了获取元素、查找、插入和删除元素的函数实现。通过示例展示了顺序表的操作过程。
6973

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



