• 链表和双链表(AcWing 826.827)


    今天我们讲的双链表和单链表是用数组的形式进行的。

    也就是用邻接表的形式完成的。

    #include<bits/stdc++.h>
    using namespace std;
    const int N =100010;
    char cp;
    int x,k;
    int idx,head;
    int a[N],Next[N];
    void init()
    {
        idx=0;
        head=-1;
    }
    void add_head(int x)
    {
        a[idx]=x;
        Next[idx]=head;
        head=idx;
        idx++;
    }
    void shanchu(int k)
    {
        if(k==0){head=Next[head];}
        else
        Next[k-1]=Next[Next[k-1]];
    }
    void charu(int k,int x)
    {
        Next[idx]=Next[k-1];
        Next[k-1]=idx;
        a[idx]=x;
        idx++;
    }
    int main()
    {
        init();
        int m;
        cin.tie(0);//优化速度,解除cin,cout捆绑
        ios::sync_with_stdio(false);//优化速度2,解除cin,scanf捆绑
        cin>>m;
        while(m--)
        {
            cin>>cp;
            if(cp=='H')
            {
                cin>>x;
                add_head(x);
            }
            if(cp=='D')
            {
                cin>>k;
                shanchu(k);
            }
            if(cp=='I')
            {
                cin>>k>>x;
                charu(k,x);
            }
        }
        while(head!=-1)
        {
            cout<<a[head]<<' ';
            head=Next[head];
        }
        return 0;
    }
    //双链表其实理解起来更加复杂,但用起来却更加方便,我们需要额外定义两个数组,和两个指针来索引我们的链表。一般情况下我们定义头节点等于0,尾节点为1.
    #include<iostream> //刚开始学的时候都非常难理解,但是你懂了还是贼**舒服好吧,建议多画图!容易加深亲们的理解噢~~ #include<algorithm> using namespace std; const int N = 100010; int a[N] , l[N], r[N]; int adx; //在k的右边加上一个x void add_to(int k,int x) { a[adx]=x; l[adx]=k; r[adx]=r[k]; l[r[k]]=adx; r[k]=adx++; } void shanchu(int k) { r[l[k]]=r[k]; l[r[k]]=l[k]; } int main() { r[0]=1; l[1]=0; adx=2; //因为数组中已有两个元素,所以adx从2开始。0 int n; cin>>n; while(n--) { string cp; cin>>cp; int k,x; if(cp=="L") { cin>>x; add_to(0,x); } else if(cp=="R") { cin>>x; add_to(l[1],x); } else if(cp=="D") { cin>>k; shanchu(k+1); } else if(cp=="IL") { cin>>k>>x; add_to(l[k+1],x); } else{ int k,x; cin>>k>>x; add_to(k+1,x); } } for(int i=r[0];i!=1;i=r[i]) cout<<a[i]<<" "; return 0; }
  • 相关阅读:
    js,jquery小知识点
    httpd.conf中文祥解(转载)
    web_report_data_point(原创)
    用lr查看apache的服务情况
    检查链接的工具
    DNS缓存(转载)
    在linux下使用用Valgrind查找内存泄漏和无效内存访问(转载)
    初次接触php
    qtp 基础代码转载自51testing中的kai_top 网友。
    descriptive programming转载51testing 作者:周坚
  • 原文地址:https://www.cnblogs.com/zyz010206/p/12369946.html
Copyright © 2020-2023  润新知