Implementing remove() Iterator Method in Java - java

So I'm working with a generic LinkedList, and I need to be able to use an iterator to remove the second half of it. However, I can't seem to get it to work. Here's the iterator call:
Iterator<String> itr = seq.iterator();
for (int i = 0; i < N / 2; i++)
{
itr.next();
}
for (int i = 0; i < N / 2; i++)
{
itr.next();
itr.remove();
}
And here's my iterator methods:
boolean canRemove = false;
int previousLoc = -1;
Node<T> current = head;
#Override
public boolean hasNext()
{
return current != null;
}
#Override
public T next()
{
if (hasNext())
{
T data = current.getData();
current = current.getLink();
previousLoc++;
canRemove = true;
return data;
}
throw new NoSuchElementException();
}
public void remove()
{
if (!canRemove)
{
throw new IllegalStateException();
}
SortedLinkedList.this.remove(previousLoc);
canRemove = false;
}
It gives a NoSuchElementException on the itr.next() call under the second for loop. My best guess is it may have something to do with the way I determine the previous node's location; the class DOES have a getPrevious() method:
private Node<T> getPrevious(T entry)
{
Node<T> previous = null;
Node<T> traverse = head;
while (traverse != null)
{
//if(entry.compareTo((T) traverse.getData()) > 0)
if (traverse.getData().compareTo(entry) < 0)
{
previous = traverse;
traverse = traverse.getLink();
}
else
{
return previous;
}
}
return previous;
}
And a getPosition method:
public int getPosition(T anEntry)
{
Node<T> traverse = head;
for (int i = 0; i < manyNodes; i++, traverse = traverse.getLink())
{
if(anEntry.compareTo(traverse.getData()) == 0)
{
return i;
}
}
throw new IllegalArgumentException("Element not in list");
}
However, if I try something like
SortedLinkedList.this.remove(getPosition((T) getPrevious((T) current)));
I get "solution.Node cannot be cast to java.lang.Comparable"
Even though the class header does extend it:
public class SortedLinkedList<T extends Comparable<? super T>> implements Iterable<T>
EDIT: Here's the remove method:
public T remove(int givenPosition)
{
T dataToReturn;
if (givenPosition < 0 || givenPosition >= manyNodes)
{
return null;
}
if (givenPosition == 0)
{
dataToReturn = head.getData();
head = head.getLink();
}
else
{
Node<T> previous = head;
for (int i = 0; i < givenPosition - 1; i++)
{
previous = previous.getLink();
}
Node<T> oneToDelete = previous.getLink();
dataToReturn = oneToDelete.getData();
previous.setLink(oneToDelete.getLink());
oneToDelete.setLink(null);
}
manyNodes--;
return dataToReturn;
}

Try something like this:
public void remove()
{
if (!canRemove)
{
throw new IllegalStateException();
}
SortedLinkedList.this.remove(previousLoc--);
canRemove = false;
}
As in your loop the calls of next() incremented the previousLoc while the remove() method removed the item from the list, it did not changed the value of previousLoc. Thus the previousLockept incrementing, while all elements were to be removed.
To see this in work, you should print out previousLoc during next() and remove()...

Related

Check that a LinkedList contains all the elements of an array

I would like to write a method public boolean containsArray(int[] arr) which returns true if all the elements of the array are in the list, otherwise it returns false.
I would like to only use the LinkedList class below.
public class LinkedList {
public Node head = null;
public class Node {
public int value;
public Node next;
Node(int value, Node next) {
this.value = value
this.next = next;
}
}
}
So far this is the code I have:
public boolean containsArray(int[] arr) {
Node tmp = head;
while(tmp.next != null) {
for(int i = 0; i < arr.length; i++) {
if(tmp.value == arr[i] {
tmp = tmp.next;
} else {
return false;
}
}
}
return true;
}
My idea is to iterate over the list while comparing the list values to the array elements but I am not sure how to implement this properly.
You should approach this in the other direction. First iterate each value of the array, and for each value look in the linked list to find it.
Also, your while condition is not entirely correct: for instance, if head is null, the while condition will trigger an exception. You should exit the loop when tmp is null, not yet when tmp.next is null.
public boolean containsArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int value = arr[i];
Node tmp = head;
while (true) {
if (tmp == null) {
return false;
}
if (tmp.value == value) {
break;
}
tmp = tmp.next;
}
}
return true;
}

How to write an add/insert method with a DoublyLinkedList in Java

I need help with my add method in java. It works with DoublyLinked List.
I am implementing a cyclic DoublyLinkedList data structure. Like a singly
linked list, nodes in a doubly linked list have a reference to the next node, but unlike a singly linked list, nodes in a doubly linked list also have a reference to the previous node. Additionally, because the list is "cyclic", the "next" reference in the last node in the list points to the first node in the list, and the "prev" reference in the first node in the list points to the last node in the list.
What the method is suppose to do is insert the value parameter at the specified index in the list. Be sure to address the case in which the list
is empty and/or the added element is the first in the list. If the index parameter is invalid, an IndexOutOfBoundsException should be thrown.
Here is my code below:
public class DoublyLinkedList<E>
{
private Node first;
private int size;
#SuppressWarnings("unchecked")
public void add(E value)
{
if (first == null)
{
first = new Node(value, null, null);
first.next = first;
first.prev = first;
}
else
{
first.prev.next = new Node(value, first, first.prev);
first.prev = first.prev.next;
}
size++;
}
private class Node<E>
{
private E data;
private Node next;
private Node prev;
public Node(E data, Node next, Node prev)
{
this.data = data;
this.next = next;
this.prev = prev;
}
}
Here is the method where it fails. I will comment the line where I'm stuck on, but other than that, what is done in the previous lines is correct from what I heard.
#SuppressWarnings("unchecked")
public void add(int index, E value)
{
if(index < 0)
{
throw new IndexOutOfBoundsException();
}
if(index > size)
{
throw new IndexOutOfBoundsException();
}
if (first.data == null)
{
throw new NullPointerException();
}
if (index == 0)
{
first = new Node(value, null, null);
first.next = first;
first.prev = first;
}
else
{
Node current = first;
for (int i = 0; i < index; i++)
{
current = current.next;
}
current.prev.next = new Node(value, current, current.prev); // This is the line where I get lost on.
current.prev = current.prev.next;
}
size++;
}
The rest of my code is here. Please focus on the method I'm working on. thank you!
#SuppressWarnings("unchecked")
public void remove(int index)
{
if(index < 0)
{
throw new IndexOutOfBoundsException();
}
if(index > size)
{
throw new IndexOutOfBoundsException();
}
if (first.data == null)
{
throw new IndexOutOfBoundsException();
}
else if (index == 0)
{
first = first.next;
}
else
{
Node current = first.next;
for (int i = 0; i < index; i++)
{
current = current.next;
}
// current.prev = current.next;
current.next = current.next.next;
}
size--;
}
#SuppressWarnings("unchecked")
public E get(int index)
{
if(index < 0)
{
throw new IndexOutOfBoundsException();
}
if(index > size)
{
throw new IndexOutOfBoundsException();
}
Node current = first;
for (int i = 0; i < index; i++)
{
current = current.next;
}
return (E) current.data;
}
#SuppressWarnings("unchecked")
public int indexOf(E value)
{
int index = 0;
Node current = first;
while (current != current.next)
{
if (current.data.equals(value))
{
return index;
}
index++;
current = current.next;
}
return index;
}
public boolean isEmpty()
{
if (size == 0)
{
return true;
}
else
{
return false;
}
}
public int size()
{
return size;
}
#SuppressWarnings("unchecked")
public String toString()
{
if (isEmpty())
{
return "[]";
}
else
{
String result = "[" + first.data;
Node current = first.next;
for(int i = 0; i < size-1; i++)
{
result += ", " + current.data;
current = current.next;
}
result += "]";
return result;
}
}
}
This was not easy at all, however I figured out the answer to my question.
#SuppressWarnings("unchecked")
public void add(int index, E value)
{
if(index > size || index < 0)
{
throw new IndexOutOfBoundsException();
}
if (first == null)
{
Node n = new Node(value, null, null);
n.next = n;
n.prev = n;
first = n;
}
else
{
Node current = first;
for (int i = 0; i < index; i++)
{
current = current.next;
}
//current points to node that will follow new node.
Node n2 = new Node(value, current, current.prev);
current.prev.next = n2;
current.prev = n2;
//update first if necessary.
if(index == 0)
{
first = n2;
}
}
size++;
}

DoublyLinkedList Issues traveling backwards

I have an assignment to complete a DoublyLinkList assignment and I am having some difficulty with two of the methods. I was given the code for MyList and MyAbstractList and was told to extend MyAbstractList with my DoublyLinkedList. I am not allowed to change MyList or MyAbstractList.
Here is the code for MyList I was provided:
public interface MyList<E extends Comparable<E>> {
/** Return true if this list contains no elements */
public boolean isEmpty();
/** Return the number of elements in this list */
public int size();
/** Add a new element at the proper point */
public void add(E e);
/** Clear the list */
public void clear();
/** Return true if this list contains the element */
public boolean contains(E e);
/** Return the element from this list at the specified index */
public E get(int index);
/** Return the first element in the list */
public E getFirst();
/** Return the last element in the list */
public E getLast();
/** Return the index of the first matching element in this list.
* Return -1 if no match. */
public int indexOf(E e);
/** Return the index of the last matching element in this list
* Return -1 if no match. */
public int lastIndexOf(E e);
/** Remove the first occurrence of the element o from this list.
* Shift any subsequent elements to the left.
* Return true if the element is removed. */
public boolean remove(E e);
/** Remove the element at the specified position in this list
* Shift any subsequent elements to the left.
* Return the element that was removed from the list. */
public boolean remove(int index);
/** Remove the first element in the list, return true if done, false if list is empty */
public boolean removeFirst();
/** Remove the Last element in the list, return true if done, false if list is empty */
public boolean removeLast();
/** Replace the element at the specified position in this list
* with the specified element and return true if done, false if index out of range. */
public boolean set(int index, E e);
}
and this was the code I was provided for MyAbstractList:
public abstract class MyAbstractList<E extends Comparable<E>> implements MyList<E> {
protected int size = 0; // The size of the list
/** Create a default list */
protected MyAbstractList() {
}
/** Create a list from an array of objects */
public MyAbstractList(E[] objects) {
for (int i = 0; i < objects.length; i++)
add(objects[i]);
}
#Override /** Return true if this list contains no elements */
public boolean isEmpty() {
return size == 0;
}
#Override /** Return the number of elements in this list */
public int size() {
return size;
}
}
Finally here is my code for MyDoublyLinkedList:
import java.util.ArrayList;
public class MyDoublyLinkedList<E extends Comparable<E>> extends MyAbstractList<E>
{
int size =0;
Node<E> head = null;
Node<E> current = null;
Node<E> tail = null;
public MyDoublyLinkedList() {
}
/** Create a list from an array of objects */
public MyDoublyLinkedList(E[] objects) {
super(objects);
}
#Override
public boolean isEmpty()
{
return size == 0;
}
#Override
public int size()
{
return size;
}
/** Add a new element at the proper point */
#Override
public void add(E e)
{
Node<E> newNode = new Node<E>(e);
if (tail == null) {
head = tail = newNode;
}
else //if (head != null)
{
tail.next = newNode;
tail = newNode;
}
size++;
}
#Override
public void clear()
{
size = 0;
head = tail = null;
}
#Override
public boolean contains(E e)
{
Node<E> current = head;
for (int i = 0; i < size; i++) {
if (current.element.equals(e))
return true;
current = current.next;
}
return false;
}
#Override
public E get(int index)
{
if (index < 0 || index > size - 1)
return null;
Node<E> current = head;
for (int i = 0; i < index; i++)
current = current.next;
return current.element;
}
#Override
public E getFirst()
{
if (size == 0) {
return null;
}
else {
return head.element;
}
}
#Override
public E getLast()
{
if (size == 0) {
return null;
}
else {
return tail.element;
}
}
#Override
public int indexOf(E e)
{
Node<E> current = head;
for (int i = 0; i < size; i++) {
if (current.element.equals(e))
return i;
current = current.next;
}
return -1;
}
#Override
public int lastIndexOf(E e)
{
int lastIndex = -1;
Node<E> current = head;
for (int i = 0; i < size; i++) {
if (current.element.equals(e))
lastIndex = i;
current = current.next;
}
return lastIndex;
}
/** Remove the first occurrence of the element o from this list.
* Shift any subsequent elements to the left.
* Return true if the element is removed. */
#Override
public boolean remove(E e)
{
int index = indexOf(e);
if (index != -1) {
return remove(index);
} else {
return false;
}
}
/** Remove the element at the specified position in this list
* Shift any subsequent elements to the left.
* Return the element that was removed from the list. */
#Override
public boolean remove(int index)
{
if (index < 0 || index >= size) {
return false;
}
else if (index == 0) {
return removeFirst();
}
else if (index == size - 1) {
return removeLast();
}
else {
Node<E> previous = head;
for (int i = 1; i < index; i++) {
previous = previous.next;
}
Node<E> current = previous.next;
previous.next = current.next;
size--;
return true;
}
}
#Override
public boolean removeFirst()
{
if (size == 0) {
return false;
}
else {
Node<E> temp = head;
head = head.next;
size--;
if (head == null) {
tail = null;
}
return true;
}
}
#Override
public boolean removeLast()
{
if (size == 0) {
return false;
}
else if (size == 1) {
Node<E> temp = head;
head = tail = null;
size = 0;
return true;
}
else {
Node<E> current = head;
for (int i = 0; i < size - 2; i++) {
current = current.next;
}
Node<E> temp = tail;
tail = current;
tail.next = null;
size--;
return true;
}
}
#Override
public boolean set(int index, E e)
{
if (index < 0 || index > size - 1)
return false;
Node<E> current = head;
for (int i = 0; i < index; i++)
current = current.next;
E temp = current.element;
current.element = e;
return true;
}
#Override
public String toString()
{
StringBuilder result = new StringBuilder("[");
Node<E> current = head;
for (int i = 0; i < size; i++) {
result.append(current.element);
current = current.next;
if (current != null) {
result.append(", "); // Separate two elements with a comma
}
else {
result.append("]"); // Insert the closing ] in the string
}
}
return result.toString();
}
public String toStringBack()
{
StringBuilder result = new StringBuilder("[");
Node<E> current = tail;
for (int i = 0; i < size; i++) {
result.append(current.element);
current = current.previous;
if (current != null) {
result.append(", "); // Separate two elements with a comma
}
else {
result.append("]"); // Insert the closing ] in the string
}
}
return result.toString();
}
public void add(int index, E e)
{
if (index ==0) {
addFirst(e);// The new node is the only node in list
}
else if(index > size)
{
addLast(e);//The index location was bigger than size
}
else
{
Node<E> current = getAtIndex(index-1);
Node<E> temp = current.next;
current.next = new Node<E>(e);
(current.next).next = temp;
size++;
}
}
public void addFirst(E e)
{
Node<E> newNode = new Node<E>(e); // Create a new node
newNode.next = head; // link the new node with the head
head = newNode; // head points to the new node
size++; // Increase list size
if (tail == null) // the new node is the only node in list
tail = head;
}
public void addLast(E e)
{
Node<E> newNode = new Node<E>(e); // Create a new for element e
if (tail == null) {
head = tail = newNode; // The new node is the only node in list
}
else {
tail.next = newNode; // Link the new with the last node
tail = tail.next; // tail now points to the last node
}
size++;
}
protected Node<E> getAtIndex(int index)
{
int count;
if (index < 0 || index > size - 1)
return null;
Node<E> temp = null;
if(index <= (size/2))
{
count = -1;
temp = head;
while(++count <= index){
temp = temp.next;
}
}
else if (index > (size/2))
{
count = size;
temp = tail;
while(--count >= index){
temp = temp.previous; //--> this is Where the null pointer exception occurs
}
}
return temp;
}
private static class Node<E>{
E element;
Node<E> next;
Node<E> previous;
public Node(E element){
this.element = element;
next = null;
previous = null;
}
}
}
When I run the add(int index, E e) Method I receive a null pointer exception in the getAtIndext() method. I also have had issues getting the add(E e) Method to add properly when I change the current location. The methods are all as I am being required to use them. The use of iterators while they would be nice are not allowed. I am using Bluj as a compiler. Please let me know what questions you have.
Thank you
EDIT: I do know what a Null Pointer Exception is, I can not figure out why this is coming back as null. The Node "current" should point to the end, then go back in the list until it reaches the indexed location. This only happens when I try to add a node in the last half of the list. The error is thrown at temp = temp.previous;
The stack trace is:
java.lang.NullPointerException at MyDoublyLinkedList.getAtIndex(MyDoublyLinkedList.java:345) at MyDoublyLinkedList.add(MyDoublyLinkedList.java:289) at TestMyDoublyLinkedList.main(TestMyDoublyLinkedList.java:50)
Edit: I figured out the issue. The add() and getAtIndex functions are running properly. When I run the test the function that is throwing a Null Pointer Exception is throwing it at position 8. It cycles through the first few nodes fine, but dies at node 8
When inserting in the add() method, you never assign previous so it is null for all nodes.

Sorting a generic LinkedList

I have to sort through a LinkedList, but i can't figure out why it only sorts it once and then stops. I am having a hard time understanding generic types and how to use them. Most of the examples i found were about sorting integer arrays, but i still couldn't translate those examples into my sort method. Anything that could help me understand how to sort this would be greatly appreciated.
public void sort() {
Node<T> current = head;
while(current != null){
if(current.getNext()!=null && current.getItem().compareTo(current.getNext().getItem()) < 0){
T temp = current.getItem();
current.setItem(current.getNext().getItem());
current.getNext().setItem(temp);
}
current = current.getNext();
}
current = head;
}
Here is my LinkedList class
public class LinkedList<T extends Comparable<T>> implements LinkedList161<T> {
protected Node<T> head;
protected int size;
public LinkedList() {
head = null;
size = 0;
}
public void add(T item, int index) {
if(index < 0 || index > size){
throw new IndexOutOfBoundsException("out of bounds");
}
if(index == 0){
head = new Node<T>(item, head);
}
else{
Node<T> current = head;
for(int i = 0; i < index -1; i ++){
current = current.getNext();
}
current.setNext(new Node<T>(item, current.getNext()));
}
size++;
}
public void addFirst(T item) {
head = new Node<T>(item, head);
size++;
}
public void addToFront(T item) {
head = new Node<T>(item, head);
size++;
}
public void addToBack(T item) {
if(head == null){
head = new Node<T>(item);
size++;
}
else{
Node<T> temp = head;
while(temp.getNext() != null){
temp = temp.getNext();
}
temp.setNext(new Node<T>(item));
size++;
}
}
public void remove(int index) {
if(index < 0 || index > size){
System.out.println("Index out of bounds");
}
if(index == 0){
head = head.getNext();
}else{
Node<T> current = head;
for(int i = 0; i < index;i++){
current = current.getNext();
}
current.setNext(current.getNext().getNext());
}
size--;
}
public T get(int index){
Node<T> p = head;
for(int i = 0; i < index;i++){
p = p.getNext();
}
return p.getItem();
}
public void clear() {
head = null;
size = 0;
}
public int size() {
return size;
}
#Override
public String toString() {
String result = "";
if (head == null)
return result;
for (Node<T> p = head; p != null; p = p.getNext()) {
result += p.getItem() + "\n";
}
return result.substring(0,result.length()-1); // remove last \n
}
#Override
public void sort() {
Node<T> current = head;
for(int i = 0; i < size;i++){
if(current.getNext()!=null && current.getItem().compareTo(current.getNext().getItem()) < 0){
T temp = current.getItem();
current.setItem(current.getNext().getItem());
current.getNext().setItem(temp);
}
current = current.getNext();
}
current = head;
}
}
Here is my Node class
public class Node<T> implements Node161<T>{
protected T item;
protected Node<T> next;
public Node(T item, Node<T> next) {
setItem(item);
setNext(next);
}
public Node(T item) {
setItem(item);
}
public T getItem() {
return item;
}
public void setItem(T i) {
item = i;
}
public void setNext(Node<T> n) {
next = n;
}
public Node<T> getNext() {
return next;
}
#Override
public String toString() {
return item.toString();
}
}
Your implementation of sort does just one step of sorting: it orders adjacent items and after this step things get better but the whole collection will not be sorted. You should repeat this step until your collection gets sorted.
Note that this algorithm is not efficient. You should look at some more sophisticated approach like merge sort
Wiki merge sort article now includes a simple but fast bottom up merge sort for linked lists that uses a small array (usually 26 to 32) of pointers to the first nodes of a list, where array[i] is either null or points to a list of size 2 to the power i. Unlike some other approaches, there's no scanning of lists, instead, the array is used along with a common merge function that merges two already sorted lists. Link to article:
http://en.wikipedia.org/wiki/Merge_sort#Bottom-up_implementation_using_lists

Implementing Singly Linked List

I am trying to learn data structure, but I ran into the dreaded NullPointerException and I am not sure how to fix it.
My SinglyLinkedList<E> class implements an interface, LinkedList, where I redefined some methods like, add(), get(), contains(), and more.
The NullPointerException happens when I use the clear() method. It points at the method removeLast() under nodeBefore.setNext(null). It also points to the clear() method under remove(head.getElement()).
Also, if there is anything I can improve upon in my code please let me know.
public class SinglyLinkedList<E> implements LinkedList<E> {
private class Node<E> {
public Node<E> next;
public E element;
public Node(E element) {
this.element = element;
}
public Node (E element, Node<E> next) {
this.element = element;
this.next = next;
}
public E getElement() {
return element;
}
public Node<E> getNext() {
return next;
}
public void setElement(E element) {
this.element = element;
}
public void setNext(Node<E> next) {
this.next = next;
}
public String toString() {
return ("[" + element + "] ");
}
}
public Node<E> head;
public Node<E> tail;
public int total;
public SinglyLinkedList() {
this.head = null;
this.tail = null;
this.total = 0;
}
public E get(int index) {
if (index < 0 || index > size()) {
return null;
}
if (index == 0) {
return head.getElement();
}
Node<E> singly = head.getNext();
for (int i = 1; i < index; i ++) {
if (singly.getNext() == null) {
return null;
}
singly = singly.getNext();
}
System.out.println("\n" + singly.getElement());
return singly.getElement();
}
public void add(E element) {
Node<E> singlyAdd = new Node<E>(element);
if (tail == null) {
head = singlyAdd;
tail = singlyAdd;
} else {
tail.setNext(singlyAdd);
tail = singlyAdd;
}
total++;
}
public void display() {
if (head == null) {
System.out.println("empty list");
} else {
Node<E> current = head;
while (current != null) {
System.out.print(current.toString());
current = current.getNext();
}
}
}
public boolean contains(E data) {
if (head == null) {
return false;
}
if (head.getElement() == data) {
System.out.println(head);
return true;
}
while (head.getNext() != null) {
head = head.getNext();
if (head.getElement() == data) {
System.out.println(head);
return true;
}
}
return false;
}
private Node<E> removeFirst() {
if (head == null) {
System.out.println("We cant delete an empty list");
}
Node<E> singly = head;
head = head.getNext();
singly.setNext(null);
total--;
return singly;
}
private Node<E> removeLast() {
Node<E> nodeBefore;
Node<E> nodeToRemove;
if (size() == 0) {
System.out.println("Empty list");
}
nodeBefore = head;
for (int i = 0; i < size() - 2; i++) {
nodeBefore = nodeBefore.getNext();
}
nodeToRemove = tail;
nodeBefore.setNext(null);
tail = nodeBefore;
total--;
return nodeToRemove;
}
public E remove(int index) {
E hold = get(index);
if (index < 0 || index >= size()) {
return null;
} else if (index == 0) {
removeFirst();
return hold;
} else {
Node<E> current = head;
for (int i = 1; i < index; i++) {
current = current.getNext();
}
current.setNext(current.getNext().getNext());
total--;
return hold;
}
}
public int size() {
return getTotal();
}
public boolean remove(E data) {
Node<E> nodeBefore, currentNode;
if (size() == 0) {
System.out.println("Empty list");
}
currentNode = head;
if (currentNode.getElement() == data) {
removeFirst();
}
currentNode = tail;
if (currentNode.getElement() == data) {
removeLast();
}
if (size() - 2 > 0) {
nodeBefore = head;
currentNode = head.getNext();
for (int i = 0; i < size() - 2; i++) {
if (currentNode.getElement() == data) {
nodeBefore.setNext(currentNode.getNext());
total--;
break;
}
nodeBefore = currentNode;
currentNode = currentNode.getNext();
}
}
return true;
}
public void clear() {
while (head.getNext() != null) {
remove(head.getElement());
}
remove(head.getElement());
}
private int getTotal() {
return total;
}
}
For your clear method, I don't see that you do any per element cleanup, and the return type is void, so all you want is an empty list. The easiest way is to simply clear everything, like in the constructor:
public void clear() {
this.head = null;
this.tail = null;
this.total = 0;
}
Another comment:
in contains, you do
while (head.getNext() != null) {
head = head.getNext();
if (head.getElement() == data) {
System.out.println(head);
return true;
}
}
which may have two problems (where the first applies to the entire class),
you compare with == data which compares references, where you probably want to compare values with .equals(data)
Edit: I.e. n.getElement().equals(data) instead of n.getElement() == data.
(Or, if n and data may be null, something like (data != null ? data.equals(n.getElement()) : data == n.getElement())
you use the attribute head as the scan variable which modifies the state of the list. Do you really want that?
The problem arises when you delete the last element within clear: remove(head.getElement());. For some reason, you first remove the head and then the tail. But when calling removeLast, you use the head (which is already null). Within removeLast this is the line, which causes the NullPointerException: nodeBefore.setNext(null);.
My advice would be to write the clear() method as #bali182 has suggested:
public void clear() {
this.head = null;
this.tail = head;
this.total = 0;
}
One advice: if you are writing methods to search or delete entries, you should never use == when dealing with objects (or even better: don't use == at all when dealing with objects). You may want to read this thread.
From within clear method, you are calling remove(head.getElement()); meaning you are trying to call LinkedList's remove method. And since you are overriding each functionality and so is add, you don't maintain internal state of LinkedList and hence you get exception. Code in remove is:
public boolean remove(Object o) {
if (o==null) {
for (Entry<E> e = header.next; e != header; e = e.next) {
if (e.element==null) {
So here since you are not using functionality of LinkedList, header would be null and doing header.next would return NullPointerException.

Categories