gpt4 book ai didi

java - 使用LinkedList的迭代器打印值,在java中不断陷入无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 07:03:58 24 4
gpt4 key购买 nike

所以我正在用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 + " ");
}

这是节点类的代码:

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;
}

最佳答案

我愿意打赌您的问题出在节点中(您不提供代码)。检查 Node.getNext() 是否实际上返回下一个节点,而不是对其自身的引用。

关于java - 使用LinkedList的迭代器打印值,在java中不断陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21685959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com