当前位置: 代码迷 >> 综合 >> 数据结构上机测试1:顺序表的应用 7.24补
  详细解决方案

数据结构上机测试1:顺序表的应用 7.24补

热度:51   发布时间:2023-10-23 09:04:08.0

数据结构上机测试1:顺序表的应用

Time Limit: 1000MS Memory limit: 65536K

题目描述

在长度为n(n<1000)的顺序表中可能存在着一些值相同的“多余”数据元素(类型为整型),编写一个程序将“多余”的数据元素从顺序表中删除,使该表由一个“非纯表”(值相同的元素在表中可能有多个)变成一个“纯表”(值相同的元素在表中只能有一个)。

输入

第一行输入表的长度n;
第二行依次输入顺序表初始存放的n个元素值。

输出

第一行输出完成多余元素删除以后顺序表的元素个数;
第二行依次输出完成删除后的顺序表元素。

示例输入

12
5 2 5 3 3 4 2 5 7 5 4 3

示例输出

5
5 2 3 4 7

提示

用尽可能少的时间和辅助存储空间。

#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <stdlib.h>
#define MAX 1002
using namespace std;
typedef struct
{
    int *elem;
    int length;
}Sq;

void initList(Sq *L)
{
    L->elem = (int *)malloc(MAX*4);
    if( !L->elem )
    {
        exit(-1);
    }
    L->length = 0;
}

void create(Sq *L, int n)
{
    int i;
    for(i = 0;i < n; i++)
    {
        scanf("%d",&L->elem[i]);
    }
    L->length = n;
}

void Del(Sq *L, int m)
{
    int *p,*q;
    p = &L->elem[m];
    for(q = p;q < p + L->length; q++)
    {
        *q = *(q+1);
    }
    L->length--;
}

void locList(Sq *L)
{
    int *p,*q;
    p = L->elem;
    while( p != L->elem + L->length )
    {
        q = p+1;
        while( q != L->elem + L->length )
        {
            if(*q == *p)
            {
                Del(L, (q - L->elem));
                q--;
            }
            q++;
        }
        p++;
    }
}

void display(Sq *L)
{
    int i;
    printf("%d\n",L->length);
    for(i = 0;i < L->length; i++)
    {
        printf(i != L->length - 1 ? "%d " : "%d\n", L->elem[i]);
    }
}

int main()
{
    int n;
    Sq L;
    scanf("%d",&n);
    initList(&L);
    create(&L, n);
    locList(&L);
    display(&L);
    return 0;
}
我终于补完了,好开心啊!

代码菜鸟,如有错误,请多包涵!!