数据结构-单链表

看了图论,发现很多都要用到链表(数组模拟)

e[N]:存储这个位置的值

ne[N]:存储下一个位置的下标

题目:

实现一个单链表,链表初始为空,支持三种操作:

  1. 向链表头插入一个数;
  2. 删除第 k个插入的数后面的一个数;
  3. 在第 k个插入的数后插入一个数。

现在要对该链表进行 M次操作,进行完所有操作后,从头到尾输出整个链表。

注意:题目中第 k个插入的数并不是指当前链表的第 k 个数。例如操作过程中一共插入了 n 个数,则按照插入的时间顺序,这 n 个数依次为:第 1 个插入的数,第 2 个插入的数,...第 n个插入的数。

输入格式

第一行包含整数 M,表示操作次数。

接下来 M行,每行包含一个操作命令,操作命令可能为以下几种:

  1. H x,表示向链表头插入一个数 x。
  2. D k,表示删除第 k个插入的数后面的数(当 k 为 0时,表示删除头结点)。
  3. I k x,表示在第 k个插入的数后面插入一个数 x(此操作中 k 均大于 0)。
输出格式

共一行,将整个链表从头到尾输出。

数据范围

1≤M≤100000

所有操作保证合法。

输入样例:
复制代码
10
H 9
I 1 1
D 1
D 0
H 6
I 3 6
I 4 5
I 4 5
I 3 4
D 6
输出样例:
复制代码
6 4 6 5

代码:

cpp 复制代码
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<string.h>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<unordered_map>
using namespace std;
typedef pair<int,int> PII;
const int N = 1e5 + 10;
int t,head,e[N],ne[N],idx;
void init(){
	head = -1;
	idx = 0;
}
void cha_head(int x){
	e[idx] = x;
	ne[idx] = head;
	head = idx;
	idx ++;
}
void delete_k(int x){
	ne[x] = ne[ne[x]];
}
void cha_k(int k,int x){
	e[idx] = x;
	ne[idx] = ne[k];
	ne[k] = idx;
	idx ++;
}
int main(){
	scanf("%d",&t);
	init();
	while(t --){
		char c;
		cin >> c;
		if(c == 'H'){
			int x;
			scanf("%d",&x);
			cha_head(x);
		}
		else if(c == 'D'){
			int k;
			scanf("%d",&k);
			if(k == 0) head = ne[head];
			delete_k(k-1);
		}else if(c == 'I'){
			int k,x;
			scanf("%d %d",&k,&x);
			cha_k(k-1,x);
		}
	}
	for(int i = head;i != -1;i = ne[i])
		cout << e[i] << ' ';
	return 0;
}

相关推荐
寒小松10 分钟前
Problem E: List练习
java·数据结构·list
↣life♚37 分钟前
从SAM看交互式分割与可提示分割的区别与联系:Interactive Segmentation & Promptable Segmentation
人工智能·深度学习·算法·sam·分割·交互式分割
zqh1767364646942 分钟前
2025年阿里云ACP人工智能高级工程师认证模拟试题(附答案解析)
人工智能·算法·阿里云·人工智能工程师·阿里云acp·阿里云认证·acp人工智能
fie88891 小时前
用模型预测控制算法实现对电机位置控制仿真
算法
Kent_J_Truman1 小时前
【交互 / 差分约束】
算法
清幽竹客1 小时前
redis数据结构-02(INCR、DECR、APPEND)
数据结构·redis
Akiiiira1 小时前
【数据结构】线性表
数据结构
ghie90901 小时前
x-IMU matlab zupt惯性室内定位算法
人工智能·算法·matlab
Magnum Lehar1 小时前
3d游戏引擎的Utilities模块实现
c++·算法·游戏引擎
小狗祈祷诗1 小时前
day20-线性表(链表II)
c语言·数据结构·链表