So i am coding a doubly linked list implementation in java and i need to print out values so that I can test to see if the code works. However, for the past couple of days ive been trying to figure out why I keep getting an infinite loop. Here's my code:
public class DoublyLinkedList<T> implements LinkedListInterface<T>, Iterable<T>{
private Node<T> head;
private Node<T> tail;
private int size;
//add, remove, clear, isempty methods, etc.
private class LinkedListIterator<E> implements java.util.Iterator<E> {
private Node<E> probe;
public LinkedListIterator(Node<T> head) {
probe = (Node<E>)(head);
}
public boolean hasNext() {
return (probe!= null);
}
public E next() {
if (!hasNext()) {
throw new NoSuchElementException("There is no element.");
}
E temp = probe.getData();
probe = probe.getNext();
return temp;
}
public void remove() {
throw new UnsupportedOperationException("We don't support this function.");
}
}
I tried printing out the values but I just get a single value repeated infinitely. What's going on? Much help would be appreciated. In main, this is what I have:
DoublyLinkedList<Integer> list = new DoublyLinkedList<Integer>();
list.add(0, 1);
list.add(1, 2);
for (Integer i : list) {
System.out.print(i + " ");
}
Here is the code for the Node Class:
public class Node<E> {
private E data;
private Node<E> next;
private Node<E> prev;
public Node(E data) {
//do I need this?
this.data = data;
}
@Override
public String toString() {
//TODO
return data + " ";
}
// Implement Methods
public E getData() {
return data;
}
public Node<E> getNext() {
return next;
}
public Node<E> getPrev() {
return prev;
}
public void setData(E e) {
data = e;
}
public void setNext(Node<E> e) {
next = e;
}
public void setPrev(Node<E> e) {
prev = e;
}
}
EDIT: Here is my add method:
public boolean add(int index, T data) {
// TODO
boolean toReturn = false;
if (data == null) return false;
if (index == 0) {
Node<T> toAdd = new Node<T>(data);
if (isEmpty()) {
head = toAdd;
tail = toAdd;
} else {
head.setPrev(toAdd);
}
toAdd.setNext(head);
head = toAdd;
toReturn = true;
} else if (index == size()) {
Node<T> toAdd = new Node<T>(data);
if (isEmpty()) {
head = toAdd;
tail = toAdd;
} else {
tail.setNext(toAdd);
toAdd.setPrev(tail);
}
tail = toAdd;
toReturn = true;
} else {
Node<T> toAdd = new Node<T>(data);
if (isEmpty()) {
head = toAdd;
tail = toAdd;
} else {
getNodeAt(index).setPrev(toAdd);
}
toAdd.setNext(getNodeAt(index));
getNodeAt(index-1).setNext(toAdd);
toReturn = true;
}
size++;
return toReturn;
}
The following is my getNodeAt() method:
private Node<T> getNodeAt(int index) {
int count = 0;
Node<T> element = head;
while (element != null) {
if (count == index) {
return element;
} else {
count++;
element = element.getNext();
}
}
return null;
}
equalsandhashcodein yourDoublyLinkedList?