静态数组下顺序表的操作
# include <stdio.h>
# include <stdlib.h>
# define MaxSize 10
typedef struct {
int data[ MaxSize] ;
int length;
} SqList;
void InitList ( SqList& L) {
for ( int i = 0 ; i < MaxSize; i++ )
L. data[ i] = 0 ;
L. length = 0 ;
}
bool ListInsert ( SqList& L, int i, int e) {
if ( i< 1 || i> L. length + 1 )
return false ;
if ( L. length >= MaxSize)
return false ;
for ( int j = L. length; j >= i; j-- )
L. data[ j] = L. data[ j - 1 ] ;
L. data[ i - 1 ] = e;
L. length++ ;
return true ;
}
bool ListDelete ( SqList& L, int i, int & e) {
if ( i< 1 || i> L. length)
return false ;
e = L. data[ i - 1 ] ;
for ( int j = i; j < L. length; j++ )
L. data[ j - 1 ] = L. data[ j] ;
L. length-- ;
return true ;
}
bool GetElem ( SqList L, int i , int & e) {
if ( i< 1 || i> L. length)
return false ;
e = L. data[ i - 1 ] ;
return true ;
}
int LocateElem ( SqList L, int e) {
int i = 0 ;
while ( i < L. length && L. data[ i - 1 ] != e)
i++ ;
if ( i >= L. length)
return 0 ;
else
return i + 1 ;
}
int main ( ) {
SqList L;
InitList ( L) ;
int e = 1 ;
if ( ListDelete ( L, 2 , e) )
printf ( "已删除第2个元素,删除的元素值为%d\n" , e) ;
else
printf ( "序位i不合法,删除失败\n" ) ;
ListInsert ( L, 5 , 2 ) ;
int ee = 0 ;
GetElem ( L, 2 , ee) ;
int i = LocateElem ( L, 5 ) ;
return 0 ;
}
动态数组下顺序表的操作
# include <stdio.h>
# include <stdlib.h>
# define InitSize 10
typedef struct {
int * data;
int MaxSize;
int length;
} SeqList;
void InitList ( SeqList& L) {
L. data = ( int * ) malloc ( InitSize * sizeof ( int ) ) ;
L. length = 0 ;
L. MaxSize = InitSize;
}
void IncreaseSize ( SeqList& L, int len) {
int * p = L. data;
L. data = ( int * ) malloc ( ( L. MaxSize+ len) * sizeof ( int ) ) ;
for ( int i = 0 ; i < L. length; i++ ) {
L. data[ i] = p[ i] ;
}
L. MaxSize = L. MaxSize + len;
free ( p) ;
}
bool ListInsert ( SeqList& L, int i, int e) {
if ( i< 1 || i> L. length + 1 )
return false ;
if ( L. length >= L. MaxSize)
return false ;
for ( int j = L. length; j >= i; j-- )
L. data[ j] = L. data[ j - 1 ] ;
L. data[ i - 1 ] = e;
L. length++ ;
return true ;
}
bool ListDelete ( SeqList& L, int i, int & e) {
if ( i< 1 || i> L. length)
return false ;
e = L. data[ i - 1 ] ;
for ( int j = i; j < L. length; j++ )
L. data[ j - 1 ] = L. data[ j] ;
L. length-- ;
return true ;
}
bool GetElem ( SeqList L, int i, int & e) {
if ( i< 1 || i> L. length)
return false ;
e = L. data[ i - 1 ] ;
return true ;
}
int LocateElem ( SeqList L, int e) {
int i = 0 ;
while ( i < L. length && L. data[ i - 1 ] != e)
i++ ;
if ( i >= L. length)
return 0 ;
else
return i + 1 ;
}
int main ( ) {
SeqList L;
InitList ( L) ;
return 0 ;
}