当前位置:   article > 正文

数据结构:顺序表中删除元素_删除顺序表中指定值的所有元素

删除顺序表中指定值的所有元素

顺序表中删除元素

前言

用于个人学习过程记录

题目

输入若干个不超过100的整数,存储到顺序表中,请写一算法,删除顺序表中所有值为item的数据元素,然后保持原数据顺序输出。
输入格式:
首先输入一个整数T,表示测试数据的组数,然后是T组测试数据。每组测试数据先在第一行输入数据个数n(n≤40)及n个不超过100的整数;
再在第二行输入一个整数,表示要删除的的数据元素item。

输出格式:
对于每组测试,保持原数据顺序输出删除顺序表中所有值为item后的数据元素,每两个数据之间留一个空格,
若删除所有值为item的数据元素后为空表,则输出“empty”。引号不必输出。

输入样例:

2
30 38 76 77 53 38 38 80 16 79 38 48 50 59 88 15 47 15 95 39 38 46 73 52 77 26 28 31 98 60 26
38
10 1 1 1 1 1 1 1 1 1 1
1
  • 1
  • 2
  • 3
  • 4
  • 5

输出样例:

76 77 53 80 16 79 48 50 59 88 15 47 15 95 39 46 73 52 77 26 28 31 98 60 26
empty
  • 1
  • 2

代码

#include<iostream>
using namespace std; 
struct LinkList{
	int *elem;
	int length;
	void Init(int n);
	void create(int n);
	void traverse();
};
void LinkList::Init(int n){
	elem = new int[n];
	length=0;
}
void LinkList::create(int n){
	Init(n);
	for(int *i=elem;i<elem+n;i++){
		cin>>*i;
		length++; 
	}
}
void LinkList::traverse(){
	for(int *i=elem;i<elem+length;i++){
		if(i!=elem)cout<<" ";
		cout<<*i;
	}
	cout<<endl;
}
void deletelist(LinkList &a,int item){
	for(int i=0;i<a.length;i++){
		if(a.elem[i]!=item) continue;
		for(int j=i;j<a.length-1;j++){
			a.elem[j]=a.elem[j+1];	
		} 
		a.length--;
		i--;		 
	}
}
int main(){
	int T;
	cin>>T;
	while(T--){
		int n;
		cin>>n;
		LinkList a;
		a.create(n);
		int item;
		cin>>item;
		deletelist(a,item);
		if(a.length>0) a.traverse();
		else{
			cout<<"empty";
		}
	}
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/439815
推荐阅读
相关标签
  

闽ICP备14008679号