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

Simple LinkedList implementation

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

Problem

I am brushing up my Data Structure knowledge (for preparation for internship interviews) and I started by implementing a very simple Linked List class. This is by no means intended to be able to replace the Java library just to be something robust enough for making me understand and remember how to implement a Linked List.

LinkedList class with private Node class:

```
public class LinkedList {

private Node _first;
private int _size;

public LinkedList() {
_first = null;
_size = 0;
}

public int getSize() {
return _size;
}

public void add(T data) {
Node current = _first;

if (current == null) {
_first = new Node(data);
_size++;
return;
}

while (current.getNext() != null) {
current = current.getNext();
}

current.setNext(new Node(data));
_size++;
}

public void add(T[] array) {
for (T data : array) {
add(data);
}
}

public void remove(T data) {
Node current = _first;
Node next = current.getNext();

if (_first.getData().equals(data)) {
if (_size == 1) {
_first.setData(null);
_size--;
return;
}
_first.setData(null);
_first = _first.getNext();
_size--;
return;
}

while (next != null) {
if (next.getData().equals(data)) {
current.setNext(next.getNext());
next = null;
_size--;
return;
}
current = next;
next = current.getNext();
}
}

private class Node {

private T _data;
private Node _next;

public Node(T data) {
_data = data;
_next = null;
}

public void setData(T data) {
_data = data;
}

public

Solution

raw types

Try to avoid raw types. private Node fieldname should be private Node fieldname, same for function returns and method arguments.

Bug

If I do this:

MyLinkedList list = new MyLinkedList<>();
list.remove("foo");


I get a NullPointerException. This is because you first access data of the root, and then check what the size is. It should be the other way around (and checking if the root is null would be a bit clearer).

You also shouldn't set the data to null, you should remove the node, otherwise you have a root node that contains null (also, your list size is wrong from there on out).

It also doesn't make that much sense to first set the data, and then override the node. In that case, just remove the setting of the data.

remove non existing element

If a non existing element is removed, you could throw a NoSuchElementException (it's what Java lists do).

Setting values to null

next = null; this isn't necessary, you are returning right afterwards.

Naming

  • it is a bit uncommon to start a field name with _.



  • I would conform to the names of the List interface (getSize -> size, add(array) -> addAll(array).

Code Snippets

MyLinkedList<String> list = new MyLinkedList<>();
list.remove("foo");

Context

StackExchange Code Review Q#65287, answer score: 11

Revisions (0)

No revisions yet.