飞行的猪哼哼

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int data[1000];
    int length;
} sqlist;

sqlist *L;
int a[1001];

void creat(int n)
{
    L=(sqlist *)malloc(sizeof(sqlist));
    int i,j;
    L->data[0]=a[0];
    L->length=1;
    for(i=1;i<n;i++)
    {
        for(j=0;j<L->length;j++)
        {
            if(a[i]==L->data[j])
                break;
        }
            if(j==L->length)
            {
                L->data[L->length]=a[i];
                L->length++;
            }

    }
}

void print(sqlist *L)
{
    int i;
    printf("%d\n",L->length);
    for(i=0;i<L->length-1;i++)
    {
        printf("%d ",L->data[i]);
    }
    printf("%d\n",L->data[L->length-1]);
}

int main()
{
    int n,i;
    scanf("%d",&n);
    for(i=0;i<=n-1;i++)
    {
        scanf("%d",&a[i]);
    }
    creat (n);
    print(L);
    return 0;
}

动态数组解决问题:

思路:主函数先用一个一维数组存储输入的数据,然后分别调用建立函数和输出函数。

  建立函数:给顺序表(动态数组)分配空间,空间第一位置赋值,长度赋值1,
            循环输入值:从第二个开始开始赋值。
  输出函数:先输出长度值,再依次输出数值。
posted on 2018-08-22 15:41  飞行的猪哼哼  阅读(139)  评论(0)    收藏  举报