小h的数列Ⅱ
题目描述
有一个初始长度为0的数列,三种操作
1.将某一个元素插入
2.将某一个元素删除
3.查询当前状态
输入
第一个数字m表示有m个操作
后面m行表示m个操作
每行输入一个数字op
如果op=1表示第一个操作,后面接着两个数字a,b表示在第a个位置插入b(a以及a后的数字后移)
如果op=2表示第二个操作,后面接着一个数字a表示删除第a数字
如果op=3表示第三个操作,查询当前数列的状态
(m<=1000,操作保证合法)
输出
对于每一个op=3输出当前数列的状态
样例输入
3
1 1 3
1 2 4
3
样例输出
3 4
简单模拟题
方法一:vector:第一次看到这个题目的时候,本能的想到用vector,动态数组的功能十分强大,而且十分的便捷,但是在写代码的过程中,编译器崩溃了,不能输入……,这里就是我又忽略的一点,vector储存的时候是在下标为0的时候开始储存的,所以我们需要在当前位置(不管删除还是增加)都要减一,不然会出现不明错误,减去1之后就顺利的AC了
#include <bits/stdc++.h>
using namespace std;
vector<int> v;
int main()
{
int m, op;
scanf("%d", &m);
for (int i = 1; i <= m; ++i)
{
scanf("%d", &op);
if (op == 1)
{
int a, b;
scanf("%d%d", &a, &b);
v.insert(v.begin() + a - 1, b);
}
else if (op == 2)
{
int x;
scanf("%d", &x);
v.erase(v.begin() + x - 1);
}
else if (op == 3)
{
for (int i = 0; i < v.size(); ++i)
if (i == 0)
printf("%d", v[i]);
else
printf(" %d", v[i]);
puts("");
}
}
return 0;
} 方法二:数组模拟:数组模拟最大的弱点就是:在数据很小的时候就可以通过,但是数组模拟不失为一种好方法,在我们想不到其他办法的时候,数组模拟就成为了我们最后一条路,此刻想到高中数学老师的一句话,如果我们想不出题解,永远有一条路在等着我们那就是求导,同样我把这句话送给后来者,虽然我知道我这一句话可能不对,但是我还是想说,如果想不到好的算法那就模拟吧!
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
int ans[maxn];
int main()
{
int op, m, now = 0;
scanf("%d", &m);
for (int i = 1; i <= m; ++i)
{
scanf("%d", &op);
if (op == 1)
{
++now;
int a, b;
scanf("%d%d", &a, &b);
for (int i = now; i > a; --i)
ans[i] = ans[i - 1];
ans[a] = b;
}
else if (op == 2)
{
int x;
scanf("%d", &x);
for (int i = x; i < now; ++i)
ans[i] = ans[i + 1];
--now;
}
else if (op == 3)
{
for (int i = 1; i <= now; ++i)
printf("%d%c", ans[i], i == now ? '\n' : ' ');
}
}
return 0;
} 方法三:链表
由于我数据结构的课在划水,所以并没有学号链表,加上之前学习C语言的时候没有去专研指针,所以目前这一块我是打算放弃了,代码的话就偷偷附上大佬的代码吧(有懒不偷***)后序有其他题解的话我都想好说辞了,(梅开二度),(帽子戏法)……
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 2e5 + 5;
const int inf = 0x3f3f3f3f;
struct node
{ //链表节点结构体
int v;
node *nex;
};
void cout_(node *head)
{ //循环输出链表的值
node *now = head->nex; //第一个元素是head的nex(head是不存东西的)
while (now != NULL)
{ //循环输出,直到链表末尾
printf("%d", now->v);
now = now->nex;
if (now != NULL)
{
printf(" ");
}
}
printf("\n");
}
int main()
{
int n, m, op, a, b;
node *head = (node *)malloc(sizeof(node)); //给头结点指针分配内存
head->nex = NULL;
scanf("%d", &m);
for (int i = 1; i <= m; ++i)
{
scanf("%d", &op);
if (op == 1)
{
scanf("%d %d", &a, &b);
a--;
node *now = head;
while (a--)
{ //找到插入位置的前一个元素
now = now->nex;
}
node *ne = (node *)malloc(sizeof(node));
//链表插入
ne->v = b;
ne->nex = now->nex;
now->nex = ne;
}
else if (op == 2)
{
scanf("%d", &a);
a--;
node *now = head;
while (a--)
{ //找到删除位置的前一个元素
now = now->nex;
}
//链表删除
node *p = now->nex;
now->nex = p->nex;
free(p);
}
else
{
//输出链表数据
cout_(head);
}
}
return 0;
}
| 想要一个东西就去买,喜欢一个人就去追,哪怕到最后那个东西没有用,喜欢的人也没有追到。都没关系,人生苦短,及时行乐,你要明白,遗憾比失败可怕的多。 |
|---|

查看22道真题和解析