顺序表应用2:多余元素删除之建表算法

来源:互联网 发布:最优化算法工程例题 编辑:程序博客网 时间:2024/06/18 17:51

Problem Description

一个长度不超过10000数据的顺序表,可能存在着一些值相同的“多余”数据元素(类型为整型),编写一个程序将“多余”的数据元素从顺序表中删除,使该表由一个“非纯表”(值相同的元素在表中可能有多个)变成一个“纯表”(值相同的元素在表中只保留第一个)。
要求:
       1、必须先定义线性表的结构与操作函数,在主函数中借助该定义与操作函数调用实现问题功能;
       2、本题的目标是熟悉在顺序表原表空间基础上建新表的算法,要在原顺序表空间的基础上完成完成删除,建表过程不得开辟新的表空间;
       3、不得采用原表元素移位删除的方式。

Input

 第一行输入整数n,代表下面有n行输入;
之后输入n行,每行先输入整数m,之后输入m个数据,代表对应顺序表的每个元素。

Output

  输出有n行,为每个顺序表删除多余元素后的结果

Example Input

45 6 9 6 8 93 5 5 55 9 8 7 6 510 1 2 3 4 5 5 4 2 1 3

Example Output

6 9 859 8 7 6 51 2 3 4 5

Hint

#include<iostream>#include<cstdlib>using namespace std;typedef struct{    int *elem;    int length;    int listsize;} List;void creat(List &L,int n) //建立顺序表{    L.elem=new int[101]; //开辟空间    if (!L.elem) //存储分配失败        exit(0);    L.length=0; //长度为零    for (int i=0; i<n; i++)    {        cin>>L.elem[i]; //输入元素        L.length++; //长度加一    }    //cout<<L.length<<endl;}int Listdelete(List &L) //删除元素{    int p = 0;    for(int i=0; i<L.length; i++)    {        int f = 0;        for(int j=0; j<p; j++)        {            if(L.elem[j] == L.elem[i])            {                f = 1;                break;            }        }        if(!f)            L.elem[p++] = L.elem[i];    }    return p;}int main(){    int n,m;    cin>>n; //输入行数    while (n--)    {        cin>>m; //每行输入        List p;        creat(p,m);//建立顺序表        int x;        x=Listdelete(p);//删除元素        for (int i=0; i<x; i++)        {            if (i==x-1)                cout<<p.elem[i]<<endl;            else                cout<<p.elem[i]<<' ';        }    }    return 0;}


阅读全文
0 0
原创粉丝点击