顺序表的基本操作:
void InitList(sqList &L);
void CreateList(sqList &L,int n);
void PrintList(sqList L);
void InsertElem(sqList &L,int i,int e);
void DeleteElem(sqList &L,int i,int &e);
int LocateElem(sqList L,int e);
int GetElem(sqList L,int i);
bool Empty(sqList L);
int Length(sqList);
结构体定义:
#define MaxSize 20
typedef struct{
int data[MaxSize];
int length;
}sqList;
运行完整代码:
#include "stdafx.h"
#include<iostream>
using namespace std;
#define MaxSize 20
typedef struct
{
int data[MaxSize];
int length;
}sqList;
void InitList(sqList &L);
void CreateList(sqList &L,int n);
void PrintList(sqList L);
void InsertElem(sqList &L,int i,int e);
void DeleteElem(sqList &L,int i,int &e);
int LocateElem(sqList L,int e);
int GetElem(sqList L,int i);
bool Empty(sqList L);
int Length(sqList);
int _tmain(int argc, _TCHAR* argv[])
{
sqList L;int e;
InitList(L);
CreateList(L,10);
cout<<"链表初始状态为:"<<endl;
PrintList(L);
InsertElem(L,5,100);
cout<<"在第5个位置,插入100后:"<<endl;
PrintList(L);
DeleteElem(L,11,e);
cout<<"删除第11个元素:"<<e<<endl;
PrintList(L);
cout<<"元素6在第"<<LocateElem(L,6)<<"个位置,";
cout<<"第8个元素为:"<<GetElem(L,8)<<"。"<<endl<<"其中";
if(Empty(L))
cout<<"链表为空,";
else
cout<<"链表非空,";
cout<<"链表当前长度为:"<<Length(L)<<endl<<endl<<endl;
system("pause");
return 0;
}
void InitList(sqList &L)
{
L.length=0;
}
void CreateList(sqList &L,int n)
{
for(int i=0;i<n;i++)
{L.data[i]=i+1;}
L.length = n;
}
void PrintList(sqList L)
{
for(int i=0;i<L.length;i++)
cout<<L.data[i]<<" ";
cout<<endl<<endl;
}
void InsertElem(sqList &L,int i,int e)
{
if(i<1||i>L.length+1||L.length==MaxSize)
cout<<"越界"<<endl;
for(int j=L.length;j>=i;j--)
L.data[j]=L.data[j-1];
L.data[i-1]=e;
L.length++;
}
void DeleteElem(sqList &L,int i,int &e)
{
if(i<1||i>L.length||L.length==0)
cout<<"越界"<<endl;
e=L.data[i-1];
for(int j=i-1;j<=L.length;j++)
L.data[j]=L.data[j+1];
L.length--;
}
int LocateElem(sqList L,int e)
{
for(int i=0;i<L.length;i++)
{
if(L.data[i]==e)
return i+1;
}
return 0;
}
int GetElem(sqList L,int i)
{
if(i<1||i>L.length)
return false;
return L.data[i-1];
}
bool Empty(sqList L)
{
return L.length==0?true:false;
}
int Length(sqList L)
{
return L.length;
}
运行结果图
![运行结果图](https://i-blog.csdnimg.cn/blog_migrate/43782368344e7506d1b44caa3834fbfb.png)