用数组模拟单链表

定义数组e[] 用来存储数据

定义数组r[] 用来存储节点的后继地址

定义数组l[] 用来存储节点的前驱地址

定义idx 来存储放入的第几个数

idx = 2,即放入的第一个数实际上是从2开始的,因此后续处理k时影加一;

画图更容易操作

Java代码实现:

import java.util.Scanner;

public class acwing827双链表 {
    static int N = 100010;
    static int[] e = new int[N];
    static int[] r = new int[N];
    static int[] l = new int[N];
    static int idx;

    public static void main(String[] args) {
        init();
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        sc.nextLine();
        while (m-->0){
            String str = sc.next();
            if (str.equals("L")){
                int x = sc.nextInt();
                insertL(x);
            } else if (str.equals("R")) {
                int x = sc.nextInt();
                insertR(x);
            } else if (str.equals("D")) {
                int k = sc.nextInt();
                delete(k+1);
            } else if (str.equals("IL")) {
                int k = sc.nextInt();
                int x = sc.nextInt();
                insertK(l[k+1],x);
            } else if (str.equals("IR")) {
                int k = sc.nextInt();
                int x = sc.nextInt();
                insertK(k+1,x);
            }
        }
        for (int i = r[0];i != 1; i = r[i]){
            System.out.print(e[i]+" ");
        }
    }
    public static void init(){
        l[1] = 0;
        r[0] = 1;
        idx = 2;
    }
    public static void insertK(int k,int x){
        e[idx] = x;
        r[idx] = r[k];
        l[r[k]] = idx;
        l[idx] = k;
        r[k] = idx++;
    }
    public static void insertR(int x){
        e[idx] = x;

        r[l[1]] = idx;
        l[idx] = l[1];
        r[idx] = 1;
        l[1] = idx++;
    }
    public static void insertL(int x){
         e[idx] = x;
         r[idx] = r[0];
         l[idx] = 0;
         l[r[0]] = idx;
         r[0] = idx++;
    }
    public static void delete(int k){
        l[r[k]] = l[k];
        r[l[k]] = r[k];

    }
}

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

彭于晏。。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值