Quick actions

cmd+k|ctrl+k

Navigation

Languages

Doubly LinkedList -> Java implementation

Snippet info

Language

Java

Visibility

public

Author

mataugigen

Created

2025-09-15T03:33:44.352985Z

Updated

2025-09-15T03:37:12.515198Z

public class DoublyLinkedList {
    
    Node head;
    Node tail;
    int length;
    
    DoublyLinkedList(int value){
        head = new Node(value);
        tail=head;
        length=1;
    }
    
    public void append(int value){
        Node newNode = new Node(value);
        tail.next = newNode;
        newNode.prev = tail;
        tail=newNode;
        length++;
    }
    
    public void  prepend(int value){
        Node newNode = new Node(value);
        newNode.next= head;
        head.prev= newNode;
        head=newNode;
        length++;
    }
    
    public void printList(LinkedList myLinkedList){
        int i=1;
        Node currentNode= myLinkedList.head;
        while(i<=myLinkedList.length){
            System.out.print(currentNode.value + " ");
            currentNode = currentNode.next;
            i++;
        }
        System.out.println();
    }
    
    public void insert(int index, int value){
        if(index==0){
            prepend(value);
        }
        else if(index==length){
            append(value);
        }
        else{
            
            Node currentNode = this.head;
            int i = 0;
            while(i<index-1 && currentNode!= null){
                currentNode=currentNode.next;
                i++;
            }
            Node newNode = new Node(value);
            newNode.next=currentNode.next;
            currentNode.next= newNode;
            this.length++;
        }
    }
    
    public void remove(int index){
        if (index < 0 || index > length) {
            System.err.println("Index Out Of Bounds For Length " + length);
        } else if (index == 0) {
            head = this.head.next;
            length--;
        } else {
            Node current = head;
            int i;
            for (i = 0; i < index - 1; i++) {
                current = current.next;
            }
            current.next = current.next.next;
            length--;
            if (i == length - 1) {
                tail = current;
            }
        }
    }
    
    public static void main(String[] args) {
        LinkedList myLinkedList = new LinkedList(10);
        myLinkedList.append(5);
        myLinkedList.append(6);
        myLinkedList.prepend(15);
        myLinkedList.printList(myLinkedList);
        myLinkedList.insert(2, 25);
        myLinkedList.printList(myLinkedList);
        myLinkedList.remove(2);
        myLinkedList.printList(myLinkedList);
        
    }
}

class Node{
    int value;
    Node next;
    Node prev;
    
    Node(int value){
        this.value = value;
        this.next=null;
        this.prev=null;
    }
}


//10-->5-->1-->3
INFO