Data Structure and Algorithms Java Version-Implementation of Single Linked List

Posted by SammyGunnz on Thu, 20 Jun 2019 23:41:50 +0200

Data structure is usually explained and implemented by c++, so it would be embarrassing if I had not studied c++ and Java, but don't think Java can't implement the tables, trees, etc. (I don't know if any students think that Java has no pointers, so some functions can't be implemented? That's wrong. This semester I learned about data structure, so I plan to implement tables, queues, stacks and trees in Java. If you are interested, you can keep an eye on my follow-up actions. My personal blog address is My blog

Last time, we shared the implementation of linear tables. I don't know if you guys did it by yourself, but the progress can't be stopped. Record the implementation of the single linked list today. Although Java does not have pointers in c++ (really not? I think so, but we can still implement linked lists. We can use reference variables to point to our nodes in Java, and let reference variables instead of pointers.

Next, let's do it step by step.

First of all, we need to know what nodes are. There is no struct in Java, but we can create a Node class to represent nodes.

public class Node<T> {
    private T data; //Node data
    public Node next; //Next node to point to
    public Node(T data, Node next) {
        this.data = data;
        this.next=next;
    }
    public Node() { }
    public T getData() {
        return data;
    }
    private void setData(T data) {
        this.data = data;
    }
}

Then we need to create a linked list LinkList class, give it some basic attribute methods, create constructors, and so on.

public class LinkList<T> {
    private Node head;  //head node
    private Node tail;  //Endpoint
    private int size;   //Link List Length

    public LinkList() {
        head=null;
        tail=null;
    }

    //Get the length of the linked list
    public int getLength(){
        return size;
    }

    //Does it contain elements?
    public boolean isEmpty(){
        return size==0;
    }

    //Clear the list
    public void clear(){
        head=null;
        tail=null;
        size=0;
    }
}

Complete the above to create a single linked list. Next, we implement the important methods in the LinkList class.

The method of retrieving nodes by index should be considered as an intermediate method to pave the way for insertion and deletion.

    //Getting Nodes by Index
    public Node getNodeByIndex(int index){
        if(index<0||index>size-1){
            throw new IndexOutOfBoundsException("Index Crossing Borders");
        }
        Node node=head;
        for(int i=0;i<size;i++,node=node.next){
            if(i==index){
                return node;
            }
        }
        return null;
    }

Insertion method: Personal suggestion to write separately (I wrote together, found that the logic would be too messy, anyway, I finally wrote separately)
- Head insertion
- tail insertion
- Intermediate insertion (including head and tail insertions in this method)

    //Head insertion
    public void  addAtHead(T element){
        head=new Node<T>(element, head);
        //If it's an empty list, let the tail pointer point to the head pointer
        if(tail==null){
            tail=head;
        }
        size++;
    }

    //Tail insertion
    public void addAtTail(T element){
        //If the table is empty
        if(head==null){
            head=new Node<T>(element, null);
            tail=head;
        }else{
            Node node=new Node<T>(element, null);
            tail.next=node;
            tail=node;  //Tail node backward
        }
        size++;
    }

    //Insert elements at specified locations
    public void insert(T element,int index){
        if(index<0||index>size){
            throw new IndexOutOfBoundsException("Index Crossing Borders");
        }
        if(index==0){
            addAtHead(element);
        }else if(index>0&&index<size-1){
            //Intermediate insertion
            Node nexNode=null;
            Node insNode=new Node<T>(element, nexNode);
            nexNode=getNodeByIndex(index);
            Node preNode=getNodeByIndex(index-1);
            preNode.next=insNode;
            insNode.next=nexNode;
            size++;
        }else {
            addAtTail(element);
        }
    }

Delete method:

- Delete the specified location element
- Delete the last element

    //Delete elements at specified locations
    public void delete(int index){
        if(index<0||index>size-1){
            throw new IndexOutOfBoundsException("Index Crossing Borders");
        }
        int flag=index-1;
        Node node=getNodeByIndex(index);
        if(flag < 0){
            //Flag < 0 indicates that the first element is deleted and that the header node is pointed to the next one.
            head=head.next;
            node=null;
        }else{
            Node preNode=getNodeByIndex(index-1);
            preNode.next=node.next;
            //If the last element is deleted, the tail node moves forward one bit
            if(index==size-1){
                tail=preNode;
            }
        }
        size--;
    }

    //Delete the last element
    public void remove(){
        delete(size-1);
    }

Finally, other methods (location, get by index, toString output arrays directly) are implemented, and the implementation of this single linked list is completed.

    @Override
    public String toString() {
        StringBuilder sb=new StringBuilder();
        Node node=head;
        for(int i=0;i<size;i++,node=node.next)
        {
            sb=sb.append(node.getData()+" ");
        }
        return sb+"";
    }

    //Get the specified location element
    public T get(int index){
        return (T) getNodeByIndex(index).getData();
    }

    //Get the index of the specified element
    public T locate(T element){
        Node node=head;
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<size;i++,node=node.next)
        {
            if(element.equals(node.getData()))
            {
                sb=sb.append(i+" ");
            }
        }
        if(sb.length()<=0)
            return (T)"No such element";
        return (T) sb;
    }

If you are too lazy to do it, you can copy and paste directly. Finally, you can attach the results of the operation.

This is the realization of single linked list. If you want to make a circular linked list, you only need to point tail tail end node to the head head node, and the interested partners can implement it by themselves.

Topics: Java Attribute