包含顺序表的建表操作
增 删(位置、值) 查
如果有错误之处,请留言指正。
#include<bits/stdc++.h>
using namespace std;
#define MaxSize 50
typedef int ElementType; //声明数据元素类型为int型
/*
包含顺序表的建表操作
增 删(位置、值) 查
*/
typedef struct SeqList
{
ElementType data[MaxSize]; //存放数据
int length; //记录当前长度
} SeqList;
/*初始化顺序表*/
void InitSeqList(SeqList &L)
{
L.length=0;
int n,i;
cout<<"请输入初始元素个数(n<=MaxSize):";
cin>>n;
for(i=0; i<n; i++)
{
cin>>L.data[i];
L.length++;
}
cout<<"初始化完成,顺序表长度为:"<<L.length<<endl;
}
int InsertSeqList(SeqList &L,ElementType x,int n)
{
int i;
if(n>L.length || n<1)
{
cout<<"插入位置不合法"<<endl;
return 0;
}
for(i=L.length; i>=n; i--)
{
L.data[i] = L.data[i-1];
}
L.data[n-1] = x;
L.length++;
}
/*按元素位置删除*/
int DeleteSeqListByPostion(SeqList &L,int postion)
{
int i;
if(postion>L.length || postion<1)
{
cout<<"位置不合法"<<endl;
return 0;
}
for(i=postion-1; i<L.length-1; i++)
{
L.data[i] = L.data[i+1];
}
L.length--;
}
/*按元素值删除*/
int DeleteSeqListByValue(SeqList &L,ElementType value)
{
int i,j;
for(i=0; i<L.length; i++)
{
if(L.data[i] == value)
{
for(j=i; j<L.length-1; j++)
{
L.data[j] = L.data[j+1];
}
L.length--;
i--;
}
}
}
/*打印值*/
void PrintSeqList(SeqList L)
{
for(int i=0; i<L.length; i++)
{
cout<<L.data[i]<<" ";
}
cout<<endl;
}
int main()
{
ElementType x;
int postion;
SeqList L;
InitSeqList(L);
PrintSeqList(L);
cout<<"请输入删除元素位置:";
cin>>postion;
DeleteSeqListByPostion(L,postion);
PrintSeqList(L);
cout<<"请输入删除元素的值:";
cin>>x;
DeleteSeqListByValue(L,x);
PrintSeqList(L);
cout<<"请输入元素的值及位置:";
cin>>x>>postion;
InsertSeqList(L,x,postion);
PrintSeqList(L);
return 0;
}
如果有错误之处,请留言指正。