# include <stdio.h>
# include <stdlib.h>
# define InitSize 10
typedef int ElemType; typedef struct { ElemType * data; ElemType MaxSize; ElemType length;
} SqList;
void PrintList ( SqList L) ;
void InitList ( SqList & L) { L. data = ( ElemType * ) malloc ( InitSize * sizeof ( ElemType) ) ; L. MaxSize = InitSize; L. length = 0 ;
}
int InsertList ( SqList & L, int i, int e) { if ( i < 1 || i > L. length || L. length == L. MaxSize) return 0 ; for ( int j = L. length; j >= i; j-- ) { L. data[ j] = L. data[ j - 1 ] ; } L. data[ i - 1 ] = e; L. length++ ; return 1 ;
}
int DeleteList ( SqList & L, ElemType i, ElemType & e) { if ( i < 0 || i >= L. length) return 0 ; printf ( "删除顺序表第%d个位置数据:%d\n" , i, L. data[ i - 1 ] ) ; for ( int j = i - 1 ; j < L. length - 1 ; j++ ) { L. data[ j] = L. data[ j + 1 ] ; } L. length-- ; return 1 ;
}
int AlterList ( SqList & L, int i, int e) { if ( i < 0 || i > L. length - 1 ) return 0 ; L. data[ i - 1 ] = e; return 1 ;
}
int GetList ( SqList L, int i) { if ( i < 0 || i > L. length) { printf ( "error" ) ; return 0 ; } return L. data[ i - 1 ] ;
}
int LocatedList ( SqList L, int e) { for ( int i = 0 ; i < L. length; i++ ) { if ( e == L. data[ i] ) return i + 1 ; } return 0 ;
}
int Length ( SqList L) { return L. length;
} bool IsEmpty ( SqList L) { if ( L. length == 0 ) return true; return false;
}
void PrintList ( SqList L) { for ( int i = 0 ; i < L. length; i++ ) { printf ( "data[%d]=%d\n" , i, L. data[ i] ) ; }
} void DestoryList ( SqList & L ) { free ( L. data) ; L. length = 0 ; L. MaxSize = 0 ; }
void IncreaseSize ( SqList & L, ElemType len) { ElemType * p = L. data; L. data = ( int * ) malloc ( ( L. MaxSize + len) * sizeof ( ElemType) ) ; for ( ElemType i = 0 ; i < L. length; i++ ) { L. data[ i] = p[ i] ; } L. MaxSize += len; free ( p) ;
}
int main ( ) { SqList L; InitList ( L) ; L. length = InitSize; for ( ElemType i = 0 ; i < L. MaxSize; i++ ) { L. data[ i] = i; } int e; printf ( "删除flag=%d\n" , DeleteList ( L, 5 , e) ) ; PrintList ( L) ; printf ( "插入flag=%d\n" , InsertList ( L, 2 , 66 ) ) ; PrintList ( L) ; printf ( "修改flag=%d\n" , AlterList ( L, 1 , 88 ) ) ; PrintList ( L) ; printf ( "按位查找%d\n" , GetList ( L, 5 ) ) ; printf ( "按值查找%d\n" , LocatedList ( L, 88 ) ) ; printf ( "顺序表的表长为%d\n" , Length ( L) ) ; printf ( "顺序表是否为空%d\n" , IsEmpty ( L) ) ; printf ( "MaxSize ==%d\n" , L. MaxSize) ; IncreaseSize ( L, 8 ) ; printf ( "MaxSize ==%d\n" , L. MaxSize) ; DestoryList ( L) ; PrintList ( L) ;
}