# include <iostream> # define MAX_SIZE 20
# define OK 1
# define ERROR 0
# define TRUE 1
# define FALSE 0 typedef int Status;
typedef int ElemType;
typedef struct
{ ElemType data[ MAX_SIZE] ; int length;
} myList;
Status InitList ( myList* list)
{ if ( list == NULL ) return ERROR; list-> length = 0 ; return OK;
}
Status ClearList ( myList* list)
{ if ( list == NULL ) return ERROR; list-> length = 0 ; return OK;
}
Status ListIsEmpty ( myList* list)
{ if ( list == NULL ) return TRUE; if ( list-> length == 0 ) return TRUE; return FALSE;
}
Status ListLength ( myList* list)
{ return list-> length;
}
Status ListInsert ( myList* list, int index, const ElemType e)
{ if ( ( list-> length == 0 ) && ( index == 1 ) ) { list-> data[ 0 ] = e; list-> length++ ; return OK; } if ( ( index <= list-> length) && ( index >= 1 ) && ( list-> length < MAX_SIZE) ) { for ( int i = list-> length - 1 ; i >= index - 1 ; i-- ) { list-> data[ i + 1 ] = list-> data[ i] ; } list-> data[ index - 1 ] = e; list-> length++ ; return OK; } return ERROR;
}
Status ListDelete ( myList* list, int index)
{ if ( ( index < list-> length) && ( index > 0 ) ) { for ( int i = index; i < list-> length; i++ ) { list-> data[ i- 1 ] = list-> data[ i] ; } list-> length-- ; return OK; } if ( ( index == list-> length) && ( index > 0 ) ) { list-> length-- ; return OK; } return ERROR;
}
Status ListTraverse ( myList* list)
{ for ( int i = 0 ; i < list-> length; i++ ) { printf ( "%d-->" , list-> data[ i] ) ; } printf ( "\r\n" ) ; return OK;
}
Status GetElem ( myList* list, int index, ElemType* e)
{ if ( ( index > 0 ) && ( index < list-> length) && ( list-> length > 0 ) ) { * e = list-> data[ index - 1 ] ; return OK; } return ERROR;
} int main ( )
{ myList list; ElemType e; Status res; int i, j; res = InitList ( & list) ; printf ( "初始化后:length = %d\n" , list. length) ; for ( i = 0 ; i < 6 ; i++ ) { res = ListInsert ( & list, 1 , i) ; } ListTraverse ( & list) ; res = ListIsEmpty ( & list) ; printf ( "list 是否为空?%d(1: 是,0: 否)\n" , res) ; ClearList ( & list) ; res = ListIsEmpty ( & list) ; printf ( "list 是否为空?%d(1: 是,0: 否)\n" , res) ; for ( i = 0 ; i < 11 ; i++ ) { res = ListInsert ( & list, 1 , i) ; } ListTraverse ( & list) ; ListInsert ( & list, 1 , 0 ) ; ListTraverse ( & list) ; GetElem ( & list, 5 , & e) ; printf ( "第5元素是%d\n" , e) ; j = list. length; res = ListDelete ( & list, j+ 1 ) ; if ( res == ERROR) printf ( "删除第%d元素失败!\n" , j + 1 ) ; else printf ( "删除第%d元素成功!\n" , j) ; res = ListDelete ( & list, j) ; if ( res == ERROR) printf ( "删除第%d元素失败!\n" , j) ; else printf ( "删除第%d元素成功!\n" , j) ; ListTraverse ( & list) ; res = ListDelete ( & list, 5 ) ; if ( res == OK) printf ( "删除第%d元素成功!\n" , 5 ) ; ListTraverse ( & list) ; return 0 ;
}