数据结构-顺序表实现(C语言)
#include <stdio.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
#define MAXSIZE 100
typedef struct {
int * elem;
int length;
} SqList;
Status InitList ( SqList * L) {
( * L) . elem= new int [ MAXSIZE] ;
if ( ! ( * L) . elem) {
printf ( "顺序表创建失败\n" ) ;
return OVERFLOW;
}
( * L) . length= 0 ;
printf ( "顺序表创建成功\n" ) ;
return OK;
}
Status GetElem ( SqList * L, int i) {
if ( i< 1 || i> ( * L) . length) {
printf ( "索引范围出错\n" ) ;
return ERROR;
}
printf ( "第%d个元素为:%d\n" , i, ( * L) . elem[ i- 1 ] ) ;
return ( * L) . elem[ i- 1 ] ;
}
int LocalElem ( SqList * L, int e) {
for ( int i = 0 ; i < ( * L) . length; i++ )
{
if ( ( * L) . elem[ i] == e) {
printf ( "元素%d的位置:%d\n" , e, i+ 1 ) ;
return i+ 1 ;
}
}
printf ( "未找到\n" ) ;
return 0 ;
}
Status ListInsert ( SqList * L, int i, int e) {
if ( ( i< 1 ) || ( i> ( ( * L) . length+ 1 ) ) ) {
printf ( "索引越界,插入失败\n" ) ;
return ERROR;
}
if ( ( * L) . length== MAXSIZE) {
printf ( "内存已满,插入失败\n" ) ;
}
for ( int j= ( * L) . length- 1 ; j>= i- 1 ; j-- ) {
( * L) . elem[ j+ 1 ] = ( * L) . elem[ j] ;
}
( * L) . elem[ i- 1 ] = e;
( * L) . length++ ;
printf ( "元素%d插入成功,顺序表长度:%d\n" , e, ( * L) . length) ;
return OK;
}
Status ListDelete ( SqList * L, int i) {
if ( ( i< 1 ) || ( i> ( * L) . length) ) {
printf ( "索引越界,删除失败\n" ) ;
return ERROR;
}
int e= ( * L) . elem[ i- 1 ] ;
for ( int j= i; j<= ( * L) . length; j++ ) {
( * L) . elem[ j- 1 ] = ( * L) . elem[ j] ;
}
( * L) . length-- ;
printf ( "第%d个元素%d删除成功\n" , i, e) ;
return OK;
}
int main ( int argc, char const * argv[ ] )
{
SqList L, * pL;
pL= & L;
InitList ( pL) ;
ListInsert ( pL, 1 , 1 ) ;
ListInsert ( pL, 2 , 3 ) ;
ListInsert ( pL, 3 , 5 ) ;
ListInsert ( pL, 4 , 7 ) ;
ListInsert ( pL, 5 , 9 ) ;
ListInsert ( pL, 6 , 11 ) ;
LocalElem ( pL, 3 ) ;
ListDelete ( pL, 6 ) ;
GetElem ( pL, 4 ) ;
printf ( "顺序表各元素:" ) ;
for ( int i = 0 ; i< L. length; i++ ) {
printf ( "%d " , L. elem[ i] ) ;
}
return 0 ;
}