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

Java code for Linked List

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

Problem

I've been practicing implementing a linked list from scratch. Can someone help review my code?

class Node {
    Node next;
    int num;

    public Node(int val) {
        num = val;
        next = null;
    }
}

public class LinkedList {

    Node head;

    public LinkedList(int val) {
        head = new Node(val);
    }

    public void append(int val) {
        Node tmpNode = head;
        while (tmpNode.next != null) {
            tmpNode = tmpNode.next;
        }
        tmpNode.next = new Node(val);
    }

    public void insert(int val) {
        Node currentNode = head;
        Node nextNode = head.next;

        if (currentNode.num > val) {
            Node tmpNode = head;
            head = new Node(val);
            head.next = tmpNode;
            return;
        }

        if (nextNode != null && nextNode.num > val) {
            currentNode.next = new Node(val);
            currentNode.next.next = nextNode;
            return;
        }

        while (nextNode != null && nextNode.num  ");
            tmpNode = tmpNode.next;
        }
        System.out.print("null");
    }

    public static void main(String[] args) {
        LinkedList myList = new LinkedList(5);
        myList.append(7);
        myList.append(16);
        myList.insert(9);
        myList.insert(4);
        myList.insert(6);
        myList.insert(17);
        myList.delete(16);
        myList.delete(5);
        myList.delete(4);
        myList.delete(17);
        myList.delete(34);
        myList.print();
    }
}

Solution

-
Your implementation does not allow for an empty list.

  • It's a bit odd to only have the constructor which takes a node value.



-
You should probably implement the List interface.

-
You should look into generics instead of hard-coding your list to only take ints.

-
It looks like from looking at insert() that you are trying to create an ordered linked list. However, append() does not. (If you really want to define an ordered linked list, you can still use generics, but you'll have to use types which are children of Comparable).

-
In insert() and delete() you have some if-conditions followed by a while-loop. My guess is that they can be merged in a single while-loop. I was lazy and haven't tried doing it, so it might not be true.

Context

StackExchange Code Review Q#31341, answer score: 7

Revisions (0)

No revisions yet.