数组模拟单双链表

这两段代码分别使用C++实现了两种链表操作。第一段代码处理'Head', 'Delete'和'Insert'指令,更新链表。第二段代码处理'Left', 'Right', 'Delete'和'Insert'指令,维护双向链表。两段代码都展示了链表的基本操作,如插入、删除和遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int>PII;
const int N = 1e5 + 10;
int head = -1, e[N], ne[N];
int tt = 0;
int main() {
	int n, k, x;
	char c;
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> c;
		if (c == 'H') {
			cin >> x;
			e[tt] = x;
			ne[tt] = head;
			head = tt++;
		} else if (c == 'D') {
			cin >> k;
			if(!k) head=ne[head];
			else ne[k-1]=ne[ne[k-1]];
		} else {
			cin >> k >> x;
			e[tt]=x;
			ne[tt]=ne[k-1];
			ne[k-1]=tt++;
		}
	}
	int temp = head;
	while (temp != -1) {
		cout << e[temp] << ' ';
		temp = ne[temp];	
	}
	return 0;
}
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int e[N],l[N],r[N],tt=0;
void insert(int k,int x)
{
	e[tt]=x;
	l[tt]=k;
	r[tt]=r[k];
	l[r[k]]=tt;
	r[k]=tt++;
}
void remove(int x)
{
	r[l[x]]=r[x];
	l[r[x]]=l[x];
}
int main()
{
	int n,k,x;
	string c;
	cin>>n;
	r[0]=1,l[1]=0;
	tt=2;
	for(int i=1;i<=n;i++)
	{
		cin>>c;
		if(c=="L")
		{
			cin>>x;
			insert(0,x);
		}
		else if(c=="R")
		{
			cin>>x;
			insert(l[1],x);
		}
		else if(c=="D")
		{
			cin>>k;
			remove(k+1);
		}
		else if(c=="IL")
		{
			cin>>k>>x;
			insert(l[k+1],x);
		}
		else if(c=="IR")
		{
			cin>>k>>x;
			insert(k+1,x);
		}
	}
	for(int i=r[0];i!=1;i=r[i])cout<<e[i]<<' ';
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值