所以我在java编写双链表实现,我需要打印出值,以便我可以测试代码是否有效。然而,在过去的几天里,我一直试图弄清楚为什么我会继续获得无限循环。这是我的代码:
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.");
}
}
我尝试打印出值,但我只是无限地重复了一个值。这是怎么回事?很多帮助将不胜感激。总的来说,这就是我所拥有的:
DoublyLinkedList<Integer> list = new DoublyLinkedList<Integer>();
list.add(0, 1);
list.add(1, 2);
for (Integer i : list) {
System.out.print(i + " ");
}
以下是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;
}
}
编辑:这是我的添加方法:
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;
}
以下是我的getNodeAt()方法:
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;
}
答案 0 :(得分:1)
我愿意打赌你的问题在Node(你不提供代码)。检查Node.getNext()实际上是否返回下一个节点,而不是对自身的引用。
答案 1 :(得分:0)
您的add
方法存在错误。当元素插入列表中间时,您的代码无法设置指向toAdd
的上一个兄弟的链接。
因此,在程序流程的某处,添加和删除元素可能会导致列表损坏。
这是我最好的猜测,而不是看你的其余代码。