顺序存储的线性表的基本操作-----C语言

#include
#define MAXSIZE 20/*分配存储空间*/
typedef int Elemtype; /*ElemType的类型根据实际情况而定*/
typedef int Status;

//创建线性表结构
typedef struct
{
Elemtype date[ MAXSIZE ]; /*数组存储数据元素,最大值MAXSIZE*/
int length; /*线性表当前的长度*/
}SqList;

//创建线性表,当输入负值时结束或长度达到MAXSIZE时结束
void CreatElem( SqList *L )
{
int i, k;
printf( "请输入数据,当输入负值时结束或长度达到MAXSIZE时结束:\n" );
scanf( "%d", &k );
for( i = 0; k >= 0 && i < MAXSIZE; i++ )
{
L->date[i] = k;
scanf( "%d", &k );
}
L->length = i;
}

//将线性表中的第i个元素返回
Status GetElem( SqList L, int i, Elemtype *e )
{
if( L.length == 0 || i < 1 || i > L.length )
return 0;
*e = L.date[ i - 1 ];
return 1;
}

//在线性表中第i个位置插入元素
Status ListInsert( SqList *L, int i, Elemtype e )
{
int k;
if( L->length == MAXSIZE )
return 0;
if( i < 1 || i > L->length + 1 )
return 0;
if( i <= L->length )
{
for( k = L->length - 1; k >= i - 1; k-- )
L->date[ k + 1 ] = L->date[ k ];
}
L->date[ i - 1 ] = e;
L->length++;
return 1;
}




//删除线性表中第i个元素
Status ListDelete( SqList *L, int i, Elemtype *e )
{
int k;
if( L->length == 0 )
return 0;
if( i < 1 || i > L->length )
return 0;
*e = L->date[ i - 1 ];
if( i < L->length )
{
for( k = i; k < L->length; k++ )
L->date[ k - 1 ] = L->date[ k ];
}
L->length--;
return 1;
}


void main()
{
int i, j;
Elemtype e;
SqList L;
CreatElem( &L );
if( L.length )
{
printf( "请输入要查找的位置:" );
scanf( "%d", &i );
if( GetElem( L, i, &e ) )
printf( "第%d个位置的元素为%d\n", i, e );
else
printf( "error\n" );
printf( "请输入要插入的位置和元素:" );
scanf( "%d%d", &i, &e );
if( ListInsert(&L, i, e) )
{
for( j = 0; j < L.length; j++ )
printf( "%d ", L.date[ j ] );
printf( "\n" );
}
else
printf( "error\n" );
printf( "请输入要删除的元素的位置:" );
scanf( "%d", &i );
if( ListDelete( &L, i, &e ) )
{
for( j = 0; j < L.length; j++ )
printf( "%d ", L.date[ j ] );
printf( "\n被删除的位置为%d,被删除的元素为%d\n", i, e );
}
else
printf( "error\n" );
}
else
printf( "error\n" );
}

    推荐阅读