已知顺序表中的元素依值递增有序排列,要求删除表中所有值相同的多余元素(使得操作后的顺序表中所有元素的值均不相同)
# include <stdio.h>
# include <stdlib.h>
# define initsize 20
typedef int ElemType;
typedef struct
{
ElemType * elem;
int length;
int listsize;
} SqList;
void IntiList ( SqList & L, int n)
{
ElemType * p;
L. elem = ( ElemType * ) malloc ( initsize* sizeof ( ElemType) ) ;
if ( ! L. elem)
{
printf ( "分配失败" ) ;
}
printf ( "请依次输入顺序表的元素(元素依值递增顺序输入):\n" ) ;
for ( p = L. elem; p < L. elem+ n; p++ )
{
scanf ( "%d" , p) ;
}
L. length = n;
L. listsize = initsize;
}
void ListDelete ( SqList & L, int i)
{
ElemType * p, * q;
if ( i< 1 || i> L. length)
{
printf ( "i值不合法\n" ) ;
}
p= L. elem+ i- 1 ;
q= L. elem+ L. length- 1 ;
for ( p++ ; p<= q; p++ )
{
* ( p- 1 ) = * p;
}
-- L. length;
}
void PrintList ( SqList L)
{
ElemType * p;
printf ( "输出顺序表中的元素\n" ) ;
for ( p= L. elem; p< L. elem+ L. length; p++ )
{
printf ( "%d\t" , * p) ;
}
printf ( "\n" ) ;
}
int main ( )
{
int i, n;
SqList L;
ElemType * p;
printf ( "请输入要建立的顺序表的长度n:\n" ) ;
scanf ( "%d" , & n) ;
IntiList ( L, n) ;
for ( i= 1 , p= L. elem; p< L. elem+ L. length; p++ , i++ )
{
if ( * ( p- 1 ) == * p)
{
ListDelete ( L, i) ;
}
}
PrintList ( L) ;
return 0 ;
}