简体   繁体   中英

implementing linked list using arrays

I am trying to implement a linked list in java using arrays as the underlying structure. However, I am not sure how to do insert an element in the array after an element and shift the array down by one

    class linkedList{
    char data[];
    int next;
    //constructor
    public linkedList(int MAX){
        data = new char[MAX];
    }

    public void insertFirst(char d){
        if(data[next]==0){
        data[next] = d;
        next++;
        }
        else{
            System.out.println("list is full");
        }
    }




    public void insertAfter (char after ,char value){
        next=0;
        while(data[next] !=after){
            next++;
        }
        char temp = data[next+1];
        data[next+1] = value;

    }

    public void printList(){
        for(int i=0;i<data.length;i++){
            System.out.print(data[i]);
        }
    }
}





public class myLinkedList {

    public static void main(String args[]) {
        linkedList list = new linkedList(9);
        list.insertFirst('T');
        list.insertFirst('H');
        list.insertFirst('L');
        list.insertAfter('H', 'z');
        list.printList();
    }

}

Also would this be considered a linked list?

This is not a linked list. What you have is similar to an ArrayList, in that an array is used as the underlying data structure. A linked list is composed of a series of nodes, with each node linked to the next. The linked list is traversed by calling something like node.next() on the current node until the target or the end of the list is reached.

If you want to insert another element into your list structure after reaching the size limit, you will need to create a new array, copy the contents of the old array over, and insert the new element into the array. You can use System.arraycopy() to perform the copying or to shift items within the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM