顺序表1(去重复值)

题目描述

在长度为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"iostream"
#include"time.h"
using namespace std;
void change(int* &a,int &size);
void show(int *a,int size);
/*
12
5 2 5 3 3 4 2 5 7 5 4 3

*/
int main(){
    /*
    int size = 10;
    int *a = new int[size];
    srand(time(NULL));
    for(int i = 0;i < size;i++){
        a[i] = rand() % 10;
    }
    */

    int size;
    cin>>size;
    int *a = new int[size];
    for(int i = 0;i < size;i++){
        cin>>a[i];
    }

//    show(a,size);
    change(a,size);
    cout<<size<<endl;
    show(a,size);
    return 0;
}
void show(int *a,int size){
    for(int i = 0;i < size;i++){
        cout<<a[i]<<" ";
    }
    cout<<endl;
}
void change(int* &a,int &size){
    int *b = new int[size];
    int lenb = 0;
    for(int i = 0;i < size;i++){
        for(int j = 0;j < lenb;j++){
            if(a[i] == b[j]){
                break;
            }
        }
        if(j==lenb){
            b[lenb++] = a[i];
        }
    }
    int *c = new int[lenb];
    for(i = 0;i < lenb;i++){
        c[i] = b[i];
    }
    int *temp = a;
    a = c;
    delete[] temp;
    delete[] b;
    size = lenb;
}

猜你喜欢

转载自www.cnblogs.com/oleolema/p/9033066.html