【发布时间】:2015-10-06 02:15:34
【问题描述】:
我正在尝试为我的循环单链表创建一个迭代器,但我不知道如何实现 next() 和 hasNext() 方法。我怀疑我需要 1) 在链表类或迭代器类中有附加字段,或者 2) 引用其他东西而不是“头”和“尾”? 我的代码如下:
public class CircularSinglyLinkedList2<E> implements Iterable<E> {
private Node head;
private Node tail;
public CircularSinglyLinkedList2() {
head = null;
tail = null;
}
class Node {
E data;
Node next;
private Node(E data) {
this.data = data;
}
}
private boolean isEmpty() {
return head == null;
}
private int size() {
int count = 0;
if(isEmpty()) {
return 0;
}
Node p = head;
count++;
p = p.next;
while(p != head) {
count++;
p = p.next;
}
return count;
}
public void insert(E data) {
Node node = new Node(data);
if(isEmpty()) {
node.next = node;
head = node;
tail = node;
} else {
node.next = head;
head = node;
tail.next = head;
}
}
public void delete(E data) {
if(isEmpty()) {
return;
}
if(head == tail) {
if(head.data == data) {
head = null;
tail = null;
}
return;
}
Node p = head.next, q = head;
while(p != head) {
if(p.data == data) {
q.next = p.next;
return;
}
q = p;
p = p.next;
}
}
public Node search(E data) {
if(isEmpty()) {
return null;
}
Node p = head;
if(p.data == data) {
return p;
}
p = p.next;
while(p != head) {
if(p.data == data) {
return p;
}
p = p.next;
}
return null;
}
public boolean contains(E data) {
return search(data) != null;
}
public Iterator<E> iterator() {
return new SLLIterator();
}
private class SLLIterator implements Iterator<E> {
private Node p;
private Node q;
public SLLIterator() {
if(!isEmpty()) {
p = head.next;
q = head;
}
}
@Override
public boolean hasNext() { doesnt't work
if(p == q || p == head) {
return false;
}
return true;
}
@Override
public E next() { //doesn't work
E data = q.data;
q = p;
p = p.next;
return data;
}
}
【问题讨论】:
-
你似乎有合理的
hasNext()和next()方法。 不起作用是什么意思? -
我插入了一些随机整数,并使用了一个 for-each 循环来打印出列表,但它没有得到所有的值。特别是,我认为它总是会错过列表中的最后一个值,即它的编写方式。
标签: java data-structures linked-list singly-linked-list circular-list