-
顺序表---C++描述 - [C++]
2008-05-25
版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://powers7.blogbus.com/logs/21602592.html
顺序表的一些简单操作:
#include<iostream>
#define MAXSIZE 100
using namespace std;
typedef struct
{
int data[MAXSIZE];
int length;
}SeqList;
SeqList SeqListInit(SeqList &L);
int SeqListInsert(SeqList &L,int i,int x);
int SeqListDelete(SeqList &L,int i);
int SeqListLocate(SeqList &L,int x);
int ListLength(SeqList &L);
int ListTraverse(SeqList &L);
int main()
{
SeqList L;
int p,i;
int q,x;
cout<<"输入一个数(顺序表的长度):"<<" ";
SeqListInit(L);
cout<<endl<<"顺序表构造完成."<<endl<<endl;
ListTraverse(L);
cout<<endl;
cout<<endl;
cout<<"插入前的长度:"<<" "<<ListLength(L)<<endl<<endl;
cout<<"插入位置第i个位置和输入元素x:"<<" ";
SeqListInsert(L,i,x);
cout<<endl;
ListTraverse(L);
cout<<endl;
cout<<endl;
cout<<"插入后顺序表的长度:"<<" "<<ListLength(L)<<endl;
cout<<endl;
cout<<"删除第i个位置上的值:"<<" ";
cout<<"删除后的长度是:"<<" "<<SeqListDelete(L,p)<<endl;
cout<<endl;
ListTraverse(L);
cout<<endl;
cout<<endl;
cout<<"输入你所要查找的值:"<<" ";
cout<<endl<<"你查找的值得位置是:"<<" "<<SeqListLocate(L,q)<<endl<<endl;
system("pause");
return 0;
}
/*********构造一个空的线性表*******/
SeqList SeqListInit(SeqList &L)
{
int i;
cin>>i;
L.length=i;
for(int j=0;j<=L.length;j++)
L.data[j]=j;
return L;
}
/********在顺序表的第i个位置插入元素**********/
int SeqListInsert(SeqList &L,int i,int x)
{
cin>>i>>x;
int j;
if(L.length==MAXSIZE)
{
cout<<"表已满"<<endl;
}
else
if(i<0||i>L.length+1)
{
cout<<"位置错"<<endl;
}
else
{
for(j=L.length-1;j>=i-1;j--)
L.data[j+1]=L.data[j];
L.data[i-1]=x;
L.length++;
}
return 0;
}
/**************删除操作****************/
int SeqListDelete(SeqList &L,int i)
{
cin>>i;
int j;
if(i<1||i>L.length)
{
cout<<"位置非法"<<endl;
}
else
{
cout<<endl;
cout<<"删除的值是:"<<" "<<L.data[i-1]<<endl<<endl;
for( j=i;j<=L.length-1;j++)
L.data[j-1]=L.data[j];
L.length--;
}
return L.length;
}
/***********按值查找***************/
int SeqListLocate(SeqList &L,int x)
{
int i=1;
cin>>x;
while(i<=L.length&&L.data[i-1]!=x)
i++;
if(i<=L.length)
{
return i;
}
else
{
return 0;
}
}
/* 求顺序表长度 */
int ListLength(SeqList &L)
{
return(L.length);
}
/***********遍历顺序表*************/
int ListTraverse(SeqList &L)
{
int i;
if(L.length<=0)
cout<<"顺序表为空"<<endl;
else
{
cout<<"顺序表中的元素为:"<<" ";
for(i=1;i<=L.length;i++)
cout<<L.data[i-1]<<" ";
}
return 0;
}随机文章:
数据库的设计范式 2008-06-27数据库范式 2008-06-27函数依赖(FD) 2008-06-27单链表---C++描述 2008-05-31二叉树---C++描述 2008-05-24
收藏到:Del.icio.us







