所以我目前正在尝试创建一个圆链表(双链表,每个值都有一个前一个,下一个值不等于null),我不确定我是否正确创建它。我的目标是能够创建一个LinkedList值,然后当我遍历列表时,hasNext()应该总是返回true(没有空值)。我认为我添加价值的方式有问题,但我不确定。这是代码,CircularList类有一个内部节点类:
public class CircularList<E> {
//I decided to still have heads and tails, to link them together
private Node<E> first = null;
private Node<E> last = null;
private Node<E> temp;
private int size;
//inner node class
private static class Node<E>{ //In this case I am using String nodes
private E data; //matching the example in the book, this is the data of the node
private Node<E> next; //next value
private Node<E> prev; //previous value
//Node constructors, also since in this case this is a circular linked list there should be no null values for previous and next
private Node(E data, Node<E> next, Node<E> prev){
this.data = data;
this.next = next;
this.prev = prev;
}
}
//end of inner node class
public void addValue(E item){
Node<E> n = new Node<E>(item, first, last);
if(emptyList() == true){ //if the list is empty
//only one value in the list
first = n;
last = n;
}
else{ //if the list has at least one value already
temp = first;
first = n;
first.next = temp;
last.next = first;
}
size++;
}
public boolean emptyList(){
boolean result = false;
if(first == null && last == null){ //if there is no values at all
result = true;
}
return result;
}
}
答案 0 :(得分:1)
刚刚进行了快速扫描,但这就是它出错的地方:
Node<E> n = new Node<E>(item, first, last);
if(emptyList() == true) {
//if the list is empty
//only one value in the list
first = n;
last = n;
}
此节点内的prev
和next
项目仍为null。你也应该设置它们。
else {
//if the list has at least one value already
temp = first;
first = n;
first.next = temp;
last.next = first;
}
此外,您不会在此处更新prev
。
还要考虑在内部使用链表作为后备数据结构,而不是您自己的节点结构。然后你只需要创建循环迭代器。