在下刚刚学习这个顺序表的排序,所以这段程序写的不咋的,见谅!
////////////////////////////// head.h ///////////////////////////////////////////////////////
#include <iostream>
using namespace std;
#define MAXSIZE 20
struct dataType
{
int key; //////以整型作为查找的类型
};
typedef dataType DataType;
struct Node
{
DataType *elem;
int lenght;
};
typedef Node SSTable;
///初始化顺序表
void initList(SSTable &S)
{
S.elem = (DataType *) malloc (MAXSIZE * sizeof(DataType) ); ///首先分配一个地址
if( ! S.elem )
{
exit(-1);
}
S.lenght=0; ///初始化长度为零(因为现在还是没有元素的)
}
bool insertList(SSTable &S, int i ,DataType d)
{//////////////////////////i代表插入的位置
DataType *p,*q;
if( i<0 || i>S.lenght+1)
{
return false;
}
if( S.lenght > MAXSIZE )
{
S.elem=( DataType *)malloc( (MAXSIZE+10)*sizeof( DataType) );
if( !S.elem )
{
return false;
}
}
q=&(S.elem[i-1]);
for( p=&( S.elem[S.lenght-1] ) ; p>=q ; --p)
{
*(p+1)=*p;
}
*q=d;
++S.lenght;
return true;
}
void showList(SSTable S)
{
for(int i=0; i<S.lenght-1; i++)
{
cout<<S.elem[i].key<<" ";
}
cout<<endl;
}
///顺着表一个一个查询
int search(SSTable S, DataType D)
{
int i=0;
while( (S.elem[i].key!=D.key) && (i<=S.lenght) )
{
i++;
}
if( i<=S.lenght )
{
return i+1;
}
else
{
return -2;
}
}
///顺着表一个一个查询2(设置一个哨兵)
int search2(SSTable S, DataType D)
{
int i =S.lenght;
int key=S.elem[0].key; ///////把第一个元素当作哨兵
while( (S.elem[i].key != D.key) && ( i>=0 ))
{
--i;
}
if( i>=0 )
{
return i+1;
}
else
{
return -2;
}
}
//////////////////////////////// main.cpp //////////////////////////////////////////////
#include "head.h"
void initList(SSTable &S);
bool insertList(SSTable &S, int i ,DataType d);
void showList(SSTable S);
int search(SSTable S, DataType D);
int search2(SSTable S, DataType D);
void main()
{
SSTable S;
initList(S);
DataType find;
for( int i=0; i<10; i++)
{
DataType d;
d.key=i*2;
insertList(S,i,d);
}
showList(S);
cout<<"输入你要查找的元素:";
cin>>find.key;
if( search(S,find)!=-2 )
{
cout<<find.key<<"在第 "<<search(S,find)<<" 个位置上!"<<endl;
}
else
{
cout<<"不存在这个元素"<<endl;
}
/////////////尝试第二中查询方法
if( search2(S,find)!=-2 )
{
cout<<find.key<<"在第 "<<search2(S,find)<<" 个位置上!"<<endl;
}
else
{
cout<<"不存在这个元素"<<endl;
}
}
1814

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



