这是蒟蒻第一次尝试单向链表,没想到RE了!题目是书本上的,在此贡上题目和我的代码以及运行结果:
给定一个长度为n的整数序列。现在有m个操作,操作分为三类,格式如下:
① 1 i:询问序列中第i个元素的值,保证i小于等于当前序列长度;
② 2 i v:在序列中第i个元素前加入新的元素v,保证i小于等于当前序列长度;
③ 3 i:删除序列中的第i个元素,保证i小于等于当前序列长度。
第一行输入n(1<=n<=1000),表示序列最初的长度。
第二行输入n个空格隔开的数表示原始的整数序列。
第三行输入m(1<=m<=1000),表示操作数。
第四到m+3行依次输入一个操作。
对于操作①输出对应的答案,一行输出一个数。
5
6 31 23 14 5
5
1 2
2 2 7
1 2
3 3
1 3
31
7
23
#include <iostream>
using namespace std;
struct Node{
int value;
Node *next;
};
Node a[2001];
int n,m;
Node * GetPos(int pos){
if(pos==0) return &a[0];
Node *p=a[0].next;
for(int i=2;i<=pos;i++)
p=p->next;
return p;
}
void InsertValue(int pos,int val){
Node *p=GetPos(pos-1);
a[n+1].value=val;
a[n+1].next=p->next;
p->next=&a[n+1];
n++; // 更新n的值
}
void DeletePos(int pos){
Node *p=GetPos(pos-1);
Node *q=GetPos(pos);
p->next=q->next;
q->value=0; q->next=NULL;
}
int main(){
a[0].next=&a[1];
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i].value;
cin>>m;
for(int i=1;i<=m;i++){
int type,pos,value;
cin>>type>>pos;
if(type==1) cout<<GetPos(pos)->value;
else if(type==2){
cin>>value;
InsertValue(pos,value);
}else if(type==3) DeletePos(pos);
}
return 0;
}
