第一次尝试单向链表就RE了!代码求调!求助书本上的题目!
  • 板块学术版
  • 楼主Xlon_WU
  • 当前回复1
  • 已保存回复1
  • 发布时间2023/8/22 11:51
  • 上次更新2023/11/3 02:01:58
查看原帖
第一次尝试单向链表就RE了!代码求调!求助书本上的题目!
958002
Xlon_WU楼主2023/8/22 11:51

这是蒟蒻第一次尝试单向链表,没想到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行依次输入一个操作。

输出格式

对于操作①输出对应的答案,一行输出一个数。

样例输入 #1

5 
6 31 23 14 5
5
1 2
2 2 7
1 2
3 3
1 3

样例输出 #1

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;
}

运行结果

2023/8/22 11:51
加载中...