B3631 单向链表(数组模拟做法

本文介绍了如何使用单向链表实现一个数据结构,支持插入元素(在指定位置后)、查询下一个元素(包括判断是否为空)以及删除元素(不改变顺序)的操作。两种方法分别给出了代码实现,并讨论了可能的优化策略。
摘要由CSDN通过智能技术生成

单向链表

题目描述

实现一个数据结构,维护一张表(最初只有一个元素 1 1 1)。需要支持下面的操作,其中 x x x y y y 都是 1 1 1 1 0 6 10^6 106 范围内的正整数,且保证任何时间表中所有数字均不相同,操作数量不多于 1 0 5 10^5 105

  • 1 x y :将元素 y y y 插入到 x x x 后面;
  • 2 x :询问 x x x 后面的元素是什么。如果 x x x 是最后一个元素,则输出 0 0 0
  • 3 x:从表中删除元素 x x x 后面的那个元素,不改变其他元素的先后顺序。

输入格式

第一行一个整数 q q q 表示操作次数。

接下来 q q q 行,每行表示一次操作,操作具体间题目描述。

输出格式

对于每个操作 2,输出一个数字,用换行隔开。

样例 #1

样例输入 #1

6
1 1 99
1 99 50
1 99 75
2 99
3 75
2 1

样例输出 #1

75
99

做法一(感觉最正确但是超时,如果数据量大于1e8感觉做法二还得离散化)

#include<iostream>

using namespace std;

const int N =105005;

int e[N],ne[N],head=-1,idx;

void init(){
	e[idx]=1;
    ne[idx]=head;
    head=idx;
    idx++;
}

int find(int x){
	for(int i=head;i!=-1;i=ne[i])
		if(e[i]==x)return i;
}

void add(int x,int y){
	e[idx]=y;
	ne[idx]=ne[x];
	ne[x]=idx;
	idx++;
}

void move(int x){
	ne[x]=ne[ne[x]];
}


int main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    int n;cin>>n;
   init();
    while(n--){
  		int op;cin>>op;
   		if(op==1){
   			int x,y;cin>>x>>y;
   			add(find(x),y);
		}else if(op==2){
			int x;cin>>x;
			int t=find(x);
			if(ne[t]!=-1)cout<<e[ne[t]]<<"\n";
			else cout<<"0\n";
		}else {
			int x;cin>>x;
			move(find(x));
		}
   }
   
}

做法二AC

#include<iostream>

using namespace std;

const int N =105005;

int e[N],ne[N],head=-1,idx;

void init(){
	e[1]=1;
	ne[1]=-1;
}


void add(int x,int y){
	e[y]=y;
	ne[y]=ne[x];
	ne[x]=y;
	
}

void move(int x){
	ne[x]=ne[ne[x]];
}


int main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    int n;cin>>n;
   init();
    while(n--){
  		int op;cin>>op;
   		if(op==1){
   			int x,y;cin>>x>>y;
   			add(x,y);
		}else if(op==2){
			int x;cin>>x;
			if(ne[x]!=-1)cout<<e[ne[x]]<<"\n";
			else cout<<"0\n";
		}else {
			int x;cin>>x;
			move(x);
		}
   }
   
}
  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值