HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Java Doubly Linked List

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
linkedlistdoublyjava

Problem

I've been working on implementing a doubly linked list from scratch in Java, and if anyone has time, could you critique it?

class Node {
    Node prev;
    Node next;
    int data;

    public Node(int d) {
        data = d;
        prev = null;
        next = null;
    }
}

class LinkedList {
    Node head;

    public LinkedList() {
        head = null;
    }

    public void insert(int d) {
        if (head == null) {
            head = new Node(d);
            return;
        }

        if (head.data > d) {
            Node holder = head;
            Node newNode = new Node(d);
            head = newNode;
            head.next = holder;
            holder.prev = newNode;
            return;
        }

        Node tmpNode = head;

        while (tmpNode.next != null && tmpNode.next.data  ");
            tmpNode = tmpNode.next;
        }

        System.out.print("null");
    }

Solution

Can use Generics for Node to provide something for more then just ints.

class Node {
    Node prev;
    Node next;
    T data;

    public Node(T data) {
        this.data = data;
        prev = null;
        next = null;
    }
}


then same for your linked list implementation.

class LinkedList {
    Node head;

    ...

    public void insert(T d) {
        if (head == null) {
            head = new Node(d);
            return;
        }

    ...


Can make T extends Comparable and use comparable interface to compare if they are less/greater than

Code Snippets

class Node<T> {
    Node prev;
    Node next;
    T data;

    public Node(T data) {
        this.data = data;
        prev = null;
        next = null;
    }
}
class LinkedList<T> {
    Node<T> head;

    ...

    public void insert(T d) {
        if (head == null) {
            head = new Node<T>(d);
            return;
        }

    ...

Context

StackExchange Code Review Q#33040, answer score: 4

Revisions (0)

No revisions yet.