zoukankan      html  css  js  c++  java
  • 数据结构(删除多余元素)

    顺序表

    题目描述

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

    输入

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

    输出

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

    示例输入

    12

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

    示例输出

    5

    5 2 3 4 7

    /..........示例代码如下(线性表实现)

     1 //线性顺序表  
     2 #include <stdio.h>  
     3 #include <stdlib.h>  
     4 #define MAXSIZE 1000 //线性表存储空间的初始分配量  
     5 #define OK 1  
     6 #define ERROR 0  
     7 #define OVERFLOW -2  
     8 typedef int elemType;//元素类型  
     9 typedef struct  
    10 {  
    11  elemType *elem;//线性表首地址  
    12  int length;//当前的长度  
    13 } SqList;  
    14 //初始化一个空的线性表  
    15 int InitList_Sq(SqList *L)  
    16 {  
    17  L->elem=new elemType[MAXSIZE];  
    18  if(!L->elem)exit(OVERFLOW);//overflow  
    19  L->length=0;//初始表为空表  
    20  return OK;  
    21 }  
    22 
    23 //遍历顺序表  
    24 void TraverseList(SqList *L)  
    25 {  
    26  int i;  
    27  for(i=0; i<L->length; i++)  
    28  {  
    29   printf("%d ",L->elem[i]);  
    30  }  
    31  printf("
    ");  
    32  return;  
    33 }    
    34 //向表尾插入元素  
    35 void InsertLast(SqList *L,elemType e)  
    36 {  
    37  
    38  if(L->length >= MAXSIZE)  
    39   return ;  
    40  L->elem[L->length]=e;  
    41  L->length++;  
    42  return;  
    43 }  
    44  
    45 
    46 void ListDelete(SqList *L,elemType i)//删除指定位置的线性表 
    47 {
    48 // if((i<1)||(i>L->length)) return;
    49  for(int j = i; j <= L->length-1; j++)
    50   L->elem[j] = L->elem[j+1];
    51  
    52  --(L->length);
    53  
    54 }
    55 //删除重复值 
    56 void DeleteElem(SqList *L)  
    57 {  
    58  
    59  for(int i = 0 ;i < L->length ;i++)
    60  {
    61   for(int j = i+1 ;j <= L->length-1 ;j++)
    62   {
    63    if(L->elem[i] == L->elem[j])
    64    {
    65     ListDelete(L,j);
    66     j--;
    67    }
    68  }
    69   
    70  }
    71  
    72  
    73 }  
    74 int main()  
    75 {  
    76  SqList list1;  
    77  InitList_Sq(&list1);  
    78  int n;  
    79  scanf("%d",&n);  
    80  int i;  
    81  elemType temp;  
    82  for(i=0; i<n; i++)  
    83  {  
    84   scanf("%d",&temp);  
    85   InsertLast(&list1,temp);  
    86  } 
    87  
    88  
    89  
    90  DeleteElem(&list1) ;
    91  printf("%d
    ",list1.length);
    92  TraverseList(&list1);
    93  
    94  return 0;  
    95 }  
  • 相关阅读:
    lntelliJ IDEA 皮肤设置
    Maven安装与配置
    lntelliJ IDEA 使用 Maven 与 每次新建项目都需要重新配置的解决方案
    Spring Boot 扫描机制说明
    Spring Boot Filter 使用指南
    Gradle构建CAS4.2.7爬坑指南
    Java的垃圾回收
    final与static
    angular directive自定义指令
    ui-router
  • 原文地址:https://www.cnblogs.com/didiaodidiao/p/9029507.html
Copyright © 2011-2022 走看看