current position:Home>Handwritten single linked list (array) of data structure (Java)

Handwritten single linked list (array) of data structure (Java)

2022-01-26 22:21:52 Everything goes with fate ~~~

import java.util.*;
import java.io.*;

class Main {
    
    static int[] e = new int[100010];//  Stored value 
    static int[] ne = new int[100010];//  Store the address of the next node , Act as a pointer 
    static int head = -1;// head: Indicates the subscript of the header node ,NULL Expressed as -1(head Not nodes , Just a pointer to a node )
    static int idx = 0;//  Indicates which node has been used 
    
    static Scanner in = new Scanner(new BufferedInputStream(System.in));//  Optimize input speed 
    //  Insert to linked list 
    static void insertToHead(int x) {
    
        e[idx] = x;//  Assign first 
        ne[idx] = head;//  Point to the head node, point to the node 
        head = idx ++ ;//  Add one to the number of nodes 
    }
    
    static void insert(int k, int x) {
    
        e[idx] = x;//  Assign first 
        ne[idx] = ne[k];//  Point to k Node to 
        ne[k] = idx ++ ;//  Add one to the number of nodes 
    }
    //  Delete node 
    static void delete(int k) {
    
        ne[k] = ne[ne[k]];// ne[ne[k]]: Indicates the address of the next node 
    }
    
    public static void main(String[] args) {
    
        int m = in.nextInt();
        while (m -- > 0) {
    
            char c = in.next().charAt(0);
            int k;
            int x;
            if (c == 'H') {
    
                x = in.nextInt();
                insertToHead(x);
            } else if (c == 'I') {
    
                k = in.nextInt();
                x = in.nextInt();
                insert(k - 1, x);// k - 1: Because the title says no k The number of inserts , The first element you want to insert , The following table is 0
            } else {
    
                k = in.nextInt();
                if (k == 0) {
    
                    head = ne[head];
                } else {
    
                    delete(k - 1);   
                }
            }
        }
        //  Start from the beginning of the node and cycle through , Output value , until i Turn into NULL( That is to say -1),i = ne[i]:i Move back one node 
        for (int i = head; i != -1; i = ne[i]) {
    
            System.out.print(e[i] + " ");
        }
    }
}

copyright notice
author[Everything goes with fate ~~~],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262221510998.html

Random recommended