數據結構(刪除多余元素)


順序表

題目描述

在長度為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("\n"); 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\n",list1.length); 92  TraverseList(&list1); 93  
94  return 0; 95 }  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM