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

描述

利用顺序表表示一个包括n个整数的序列,请实现一个时间复杂度为O(n),空间复杂度为O(1)的算法,该算法可以删除表中所有值为item的元素。

输入

多组数据,每组数据有三行,第一行为顺序表的长度n,第二行为顺序表的n个元素(元素之间用空格分隔),第三行为待删除的元素的值item。当n=0时输入结束。

输出

对于每组数据分别输出一行,依次输出删除值为item的元素后顺序表中的剩余元素,元素之间用空格分隔。

输入样例 1 

5
44 11 22 33 22
11
6
22 33 11 33 33 55
33
0

输出样例 1

44 22 33 22
22 11 55


#include<stdio.h>
#include<string.h>
#include<iomanip>
#include<iostream>
#define OK 1
#define OVERFLOW -2
#define MAXSIZE 1000 
using namespace std;
typedef struct
{
   int data;
   
}LNode;

typedef struct
{
	LNode *elem;
	int length;
}Sqlist;

int InitList(Sqlist &L){
	L.elem = new LNode[MAXSIZE];
	if(!L.elem) exit(OVERFLOW);
	L.length = 0;
	return OK;
}

int Input(Sqlist &L,int n){
	int i;
	for( i = 0; i<n; i++)
	   { 
	     cin>>L.elem[i].data;
	       L.length++;
    	}
		return OK;   
}
void Delete(Sqlist &L){
     int item;
     cin>>item;
     int n = 0;//记录不等于item的元素个数 
     for(int i = 0;i<L.length;i++){ //从前往后扫描 
     	 if(L.elem[i].data !=item){
     	 	L.elem[n].data =L.elem[i].data; //利用原表的空间记录值不为item的元素 
     	 	n++;
     	 }
		  
	 }
	L.length = n;	 
}
int Output(Sqlist &L){
	
	 for(int i=0;i<L.length-1;i++)
      {
		cout<<L.elem[i].data<<" ";
      }
      cout<<L.elem[L.length-1].data<<endl;
      
	 return OK;
}
int main(){
	int num;
	while(cin>>num&&num!=0){
	   Sqlist L; 
	   InitList(L);
	   Input(L,num);
	   Delete(L);
	   Output(L);
	}	
	return 0;
}

  • 8
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yvonnae

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值