Problem Description
在长度为n(n<1000)的顺序表中可能存在着一些值相同的“多余”数据元素(类型为整型),编写一个程序将“多余”的数据元素从顺序表中删除,使该表由一个“非纯表”(值相同的元素在表中可能有多个)变成一个“纯表”(值相同的元素在表中只能有一个)。
Input
第一行输入表的长度n;
第二行依次输入顺序表初始存放的n个元素值。
Output
第一行输出完成多余元素删除以后顺序表的元素个数;
第二行依次输出完成删除后的顺序表元素。
Sample Input
12 5 2 5 3 3 4 2 5 7 5 4 3
Sample Output
5 5 2 3 4 7
Hint
用尽可能少的时间和辅助存储空间。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define LISTSIZE 1000
#define LISTINCREAMENT 10
#define OVERFLOW -1
#define OK 1
#define ERROR 0
typedef int ElemType;
typedef struct
{
ElemType * elem;
int length;
int listsize;
}Sqlist;
int InitList(Sqlist *L);
int ListInsert(Sqlist *L,int i,ElemType e);
void pure(Sqlist *L);
int main()
{
Sqlist L;
int i,n,elem;
scanf("%d",&n);
InitList(&L);
for(i=1;i<=n;i++)
{
scanf("%d",&elem);
ListInsert(&L,i,elem);
}
pure(&L);
printf("%d\n",L.length);
for(i=1;i<=L.length;i++)
{
if(i!=L.length)
printf("%d ",L.elem[i-1]);
else
printf("%d\n",L.elem[i-1]);
}
return 0;
}
int InitList(Sqlist *L)
{
L->elem=(ElemType *)malloc(LISTSIZE*sizeof(ElemType));
if(!L->elem)exit(OVERFLOW);
L->length=0;
L->listsize=LISTSIZE;
return OK;
}
int ListInsert(Sqlist *L,int i,ElemType e)
{
if(i<1||i>L->length+1)return ERROR;
if(L->length>=L->listsize)//如果存储空间已满,则增加分配
{
ElemType * newbase=(ElemType*)realloc(L->elem,
(L->listsize+LISTINCREAMENT)*sizeof(ElemType));
if(!newbase)exit(OVERFLOW);//存储分配失败
L->elem=newbase;
L->listsize+=LISTINCREAMENT;
}
ElemType * q=&(L->elem[i-1]);
ElemType * p;
for(p=&(L->elem[L->length-1]);p>=q;--p)
*(p+1)=*p;
*q=e;
++L->length;
return OK;
}
void pure(Sqlist *L)
{
int i,j,k;
for(i=0;i<L->length-1;i++)
{
j=i+1;
while(j<L->length)
{
if(L->elem[j]!=L->elem[i])
++j;
else
{
for(k=j+1;k<L->length;++k)
{
L->elem[k-1]=L->elem[k];
}
--L->length;
}
}
}
}