0
点赞
收藏
分享

微信扫一扫

C++数组模拟单链表与双链表

草原小黄河 2022-02-15 阅读 103

https://www.acwing.com/problem/content/828/

#include<bits/stdc++.h>
using namespace std;
const int N=100005;
int ne[N],value[N];
char op;
int n,x,w,head,y;
int main(){
    cin>>n;
    while(n--){
        cin>>op;
        if(op=='H'){
            cin>>x;
            w++;
            value[w]=x;
            ne[w]=head;
            head=w;
        }else if(op=='D'){
            cin>>x;
            if(x==0)head=ne[head];
            else ne[x]=ne[ne[x]];
        }else{
            cin>>x>>y;
            w++;
            value[w]=y;
            ne[w]=ne[x];
            ne[x]=w;
        }
    }
    while(head!=0)cout<<value[head]<<" ",head=ne[head];
    return 0;
}

https://www.acwing.com/problem/content/829/
为了方便处理,构建一个虚拟头节点与虚拟尾节点

#include<bits/stdc++.h>
using namespace std;
const int N=100005;
int l[N],r[N],val[N];
int w,x,k;
string op;
int n;
void insert(int k,int x){
    w++;
    l[w]=k;
    r[w]=r[k];
    r[k]=w;
    l[r[w]]=w;
    val[w]=x;
}
void remove(int k){
    r[l[k]]=r[k];
    l[r[k]]=l[k];
}
int main(){
    r[0]=1;
    l[1]=0;
    w=1;
    cin>>n;
    while(n--){
        cin>>op;
        if(op=="L"){
            cin>>x;
            insert(0,x);
        }else if(op=="R"){
            cin>>x;
            insert(l[1],x);
        }else if(op=="D"){
            cin>>x;
            remove(x+1);
        }else if(op=="IL"){
            cin>>k>>x;
            insert(l[k+1],x);
        }else{
            cin>>k>>x;
            insert(k+1,x);
        }
    }
    for(int now=r[0];now!=1;now=r[now])cout<<val[now]<<" ";
    return 0;
}

举报

相关推荐

0 条评论