In Java, I have to create a linked list from scratch (not allowed to use the LinkedList import).
I have been provided with this code as support:
public class Link<E> {
private E e; // the element contained in this linked list
private Link<E> next; // the next element of the linked list
public Link(E e, Link<E> n) {
this.e = e;
this.next = n;
}
public Link(E e) {
this.next = null;
this.e = e;
}
/**
* Method to set the element
*/
public void setElement(E e) {
this.e = e;
}
/**
* Method to set the next linked list element
*/
public void setNext(Link<E> e) {
this.next = e;
}
/**
* Method to get the element.
*/
public E getElement() {
return this.e;
}
/**
* Method to get the next linked list element
*/
public Link<E> getNext() {
return this.next;
}
}
With this code provided, I have to create a LinkedList with the following methods:
Add objects at a specific index; addAt(data, index)
Retrieve objects using the index; getAt(index i)
I have come up with the following code:
import java.util.*;
public class LinkedList<E> {
private Link<E> head, tail;
protected long size;
public LinkedList() {
super();
this.head = null;
this.tail = null;
this.size = 0;
}
public void addAt(Object data, int index) {
Link<E> temp = new Link(data);
Link<E> current = head;
if (data == null) {
throw new NoSuchElementException();
}
if (current != null) {
// crawl to the requested index or the last element in the list, whichever comes
// first
for (int i = 0; i < index && current.getNext() != null; i++) {
current = current.getNext();
}
}
// set the new node's next-node reference to this node's next-node reference
temp.setNext(current.getNext());
// now set this node's next-node reference to the new node
current.setNext(temp);
}
public Object get(int index)
// returns the element at the specified position in this list.
{
// index must be 1 or higher
if (index < 0)
return null;
Link<E> current = null;
if (head != null) {
current = head.getNext();
for (int i = 0; i < index; i++) {
if (current.getNext() == null)
return null;
current = current.getNext();
}
return current.getElement();
}
return current;
}
}
However, I get a NullPointerException which I can't wrap my head around at:
temp.setNext(current.getNext());
Besides the NPE, I have another question: would there be a cleaner way to implement a LinkedList from scratch?