[c++]代码库
#include<iostream.h>
#include<stdlib.h>
typedef int elemtype;
struct list
{
elemtype *list;
int len;
int maxsize;
};
void initlist ( list &l,int ms )
{
l.list=new elemtype[ms];
if ( !l.list )
{
cerr<<"memory allocation failure!"<<endl;
exit ( 1 );
}
l.len=0;
l.maxsize=ms;
}
void clearlist ( list &l )
{ l.len=0;}
int length ( list &l )
{ return l.len; }
int listempty ( list &l )
{ return l.len==0;}
int listfull ( list &l )
{ return l.len==l.maxsize;}
void looklist ( list &l )
{
for ( int i=0; i<l.len; i++ )
cout<<l.list[i]<<' ';
cout<<endl;
}
int findlist ( list &l,elemtype x )
{
for ( int i=0; i<l.len; i++ )
if ( l.list[i]==x )
{
x=l.list[i];
return 1;
}
return 0;
}
int insertlist ( list &l,elemtype x,int k )
{
if ( listfull ( l ) ) return 0;
if ( k>0 )
{
for ( int i=l.len-1; i>=0; i-- )
l.list[i+1]=l.list[i];
l.list[0]=x;
}
else if ( k<0 ) l.list[l.len]=x;
else
{
for ( int i=0; i<l.len; i++ )
if ( x<l.list[i] ) break;
for ( int j=l.len-1; j>=i; j-- )
l.list[j+1]=l.list[j];
l.list[i]=x;
}
l.len++;
return 1;
}
int deletelist ( list &l,elemtype &x,int k )
{
if ( listempty ( l ) ) return 0;
if ( k>0 )
{
x=l.list[0];
for ( int i=1; i<l.len; i++ )
l.list[i-1]=l.list[i];
}
else if ( k<0 ) x=l.list[l.len-1];
else
{
for ( int i=0; i<l.len; i++ )
if ( l.list[i]==x ) break;
if ( i>=l.len )
return 0;
else x=l.list[i];
for ( int j=i+1; j<l.len; j++ )
l.list[j-1]=l.list[j];
}
l.len--;
return 1;
}
void outputlist ( list &l,int m )
{
int *b=new int[l.len];
int i,k;
for ( i=0; i<l.len; i++ ) b[i]=i;
for ( i=1; i<l.len; i++ )
{
k=i-1;
for ( int j=i; j<l.len; j++ )
{
if ( m==1&&l.list[b[j]]<l.list[b[k]] ) k=j;
if ( m!=1&&l.list[b[j]]>l.list[b[k]] ) k=j;
}
if ( k!=i-1 )
{
int x=b[i-1];
b[i-1]=b[k];
b[k]=x;
}
}
for ( i=0; i<l.len; i++ )
cout<<l.list[b[i]]<<' ';
cout<<endl;
}
void main()
{
const int ml=20;
list a;
initlist ( a,ml );
int i;
elemtype x;
cout<<"input 5 int num:";
for ( i=0; i<5; i++ )
{
cin>>x;
insertlist ( a,x,-1 );
}
cout<<"input 2 int num:";
cin>>x;
insertlist ( a,x,1 );
cin>>x;
insertlist ( a,x,1 );
looklist ( a );
cout<<"uporder sort:";
outputlist ( a,1 );
cout<<"downorder sort:";
outputlist ( a,0 );
list b;
initlist ( b,ml );
for ( i=0; i<a.len; i++ )
insertlist ( b,a.list[i],0 );
looklist ( b );
if ( deletelist ( a,x,1 ) )
cout<<"delete front!"<<endl;
else
cout<<"delete fale!"<<endl;
looklist ( a );
if ( deletelist ( a,x,-1 ) )
cout<<"delete rear!"<<endl;
else
cout<<"delete fale!"<<endl;
looklist ( a );
cout<<"input a del num:";
cin>>x;
if ( deletelist ( a,x,0 ) )
cout<<"delete success!"<<endl;
else
cout<<"delete fale!"<<endl;
looklist ( a );
}