Realize a simple linked list by yourself

Keywords: Programming

In the near future, I want to learn algorithms, so I started from the list, wrote the following code in association with the basic structure of the list, found some problems in the process of writing, and then gradually improved it. For example, when I first inserted it, I found a null node through circulation and then inserted it. Later, I thought that if the number of nodes is large, it will seriously affect the performance, so I changed it to For now, blog content is just a personal note.

Node{
    private String key;
    private Object val;
    private Node next;

}

   private Node eden;
    private Node parent; // Current node
    private AtomicInteger size = new AtomicInteger(0);
    public void put(String k, Object v) {
        if(k == null || "".equals(k)){
            throw new NullPointerException("put fail, key must not be null");
        }

        size.incrementAndGet();
        synchronized (this){
            if (eden == null) {
                // The initial node does not store anything
                parent = eden = new Node();
            }

            Node next = new Node();
            next.setKey(k);
            next.setVal(v);
            parent.setNext(next);
            parent = next;
        }

    }

    public int size() {
        return size.get();
    }

    private Node getNext(Node n) {
        return n.getNext();
    }

    public Node get(String k) {
        if(k == null || "".equals(k)){
            throw new NullPointerException("get fail, key must not be null");
        }

        Node nd = getNext(eden);
        Node result = null;
        while (true) {
            if (nd == null) {
                break;
            }
            if (!nd.getKey().equals(k)) {
                nd = getNext(nd);
                continue;
            }
            result = nd;
            break;
        }
        return result;
    }

    public static void main(String[] args) {
        NodeFade nf = new NodeFade();
        nf.put("a", 1 << 1);
        nf.put("b", 2 << 1);
        nf.put("c", 3 << 1);
        nf.put("d", 4 << 1);
        System.out.println(nf.size());
        System.out.println(nf.get("d") == null ? null : nf.get("d").getVal());
        // nf.put(null, 11);
        // System.out.println(nf.get(null));


    }

Posted by abigail on Tue, 21 Apr 2020 07:49:33 -0700