题目描述:线性表的实现
问题描述实验要求 :
基于教材内容(shaffer),实现线性表。
基本要求
需要基于顺序表(数组)或链表来实现线性表ADT 需要实现线性表的各个基本操作 编写一个demo程序,测试线性表的各个基本操作的功能是否正常
#include<iostream>
#define ListSize 100
using namespace std;
typedef int DataType;
typedef struct
{
DataType data[ListSize];
int length;
}SeqList;
void InitList(SeqList *sl)
{
sl->length=0;
}
void CreateList(SeqList *sl,DataType x[],int n)
{
int i;
for(i=0;i<n;i++)
{
sl->data[i]=x[i];
sl->length++;
}
}
int LengthList(SeqList *sl)
{
return sl->length;
}
DataType GetList(SeqList *sl,int k)
{
return sl->data[k-1];
}
int InsertList(SeqList *sl,DataType x,int i)
{
int j;
if(i<0||i>sl->length+1)
{
cout<<"Position error."<<endl;
return 0;
}
if(sl->length>=ListSize)
{
cout<<"Overflow."<<endl;
return 0;
}
for(j=sl->length-1;j>=i-1;j--)
sl->data[j+1]=sl->data[j];
sl->data[i-1]=x;
sl->length++;
return 1;
}
int DeleteList(SeqList *sl,int i)
{
int j;
if(i<1||i>sl->length)
{
cout<<"Position error";
return 0;
}
if(sl->length==0)
{
cout<<"Position error";
return 0;
}
for(j=i;j<=sl->length-1;j++)
sl->data[j-1]=sl->data[j];
sl->length--;
return 1;
}
int SearchList(SeqList *sl,DataType x)
{
int i=1;
while(i<=sl->length&&sl->data[i-1]!=x)
i++;
if(sl->data[i-1]==x)
return i;
else
return -1;
}
void PrintList(SeqList *sl)
{
int i;
for(i=0;i<LengthList(sl);i++)
{
cout<<sl->data[i]<<" ";
}
cout<<endl;
}
int main()
{
SeqList *seq;
cout<<"The sequence list length is:"<<endl;
int n;
cin>>n;
cout<<"The sequence list is:"<<endl;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
seq=(SeqList *)malloc(ListSize * sizeof(SeqList));
InitList(seq);
CreateList(seq,arr,n);
int s;
cin>>s;
cout<<"The "<<s<<" node is "<<GetList(seq,s)<<endl;
cout<<"Insert a node,the sequence list is:"<<endl;
int m,x;
cin>>m>>x;
InsertList(seq,m,x);
cout<<"The sequence list is:"<<endl;
PrintList(seq);
int q;
cin>>q;
DeleteList(seq,q);
cout<<"Delete a node,the sequence list is:"<<endl;
PrintList(seq);
int p;
cin>>p;
if(SearchList(seq,p)!=-1)
cout<<"The search data"<<p<<" has been found. The code is "<<SearchList(seq,p)<<endl;
else
cout<<"The search data not found."<<endl;
cout<<"The sequence list length is "<<LengthList(seq);
return 0;
}