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

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

描述

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

输入

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

输出

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

demo

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

//结点
typedef struct Lnode {
	int data;
	struct Lnode *next;
}Lnode,*Linklist;

//尾插建表
void Creatlist(Linklist &L,int &e) {
	Lnode *p = new Lnode;
	p->data = e;
	p->next = NULL;

	Lnode *cur = L;
	while (cur->next)
	{
		cur = cur->next;
	}
	cur->next = p;
	p->next = NULL;

}
//初始化
void Initlist(Linklist &L) {
	L = new Lnode;
	L->next = NULL;
}

//删除指定节点
void Clear(Linklist &L, int &item) {
	
	Lnode *cur = L;
	while (cur->next)
	{
		if (cur->next->data == item) {
			cur->next = cur->next->next;
		}
		else
		{
			cur = cur->next;
		}
	}
}
//打印
void Print(Linklist &L) {
	Lnode *cur = L->next;
	while (cur->next)
	{
		cout << cur->data << " ";
		cur = cur->next;
	}
	cout << cur->data << endl; //处理最后一个空格
}
int main() {
	int n;
	while (scanf("%d",&n)!=EOF)
	{
		if (n == 0) break;
		Linklist L;
		Initlist(L);

		for (int i = 0; i < n; i++) { //建表
			int e;  cin >> e;
			Creatlist(L, e);
		}
		int item; //指定值
		cin >> item;
		Clear(L, item);
		Print(L);
	}
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值