[英]Iterate through a linked list in Java while filtering directly in the next() method?
我在CS作業中遇到了一些問題。 我需要用Java寫一個鏈表,然后只用一個迭代器迭代奇數。 本質上,forEach循環必須僅通過奇數進行迭代。
到目前為止,我的LinkedList類中只有這個:
public class Iterator implements java.util.Iterator<Integer> {
private Node nextNode;
public Iterator(){
nextNode = head_;
}
@Override
public boolean hasNext() {
return (nextNode != null);// && (nextNode.data_ % 2 != 0);
}
@Override
public Integer next() {
if (!hasNext()) throw new NoSuchElementException();
Integer data = nextNode.data_;
nextNode = nextNode.next_;
return data;
}
public void remove(){
throw new UnsupportedOperationException();
}
}
public Iterator iterator() {
return new Iterator();
}
如果我取消注釋&& (nextNode.data_ % 2 != 0);
,則僅打印第一個數字(碰巧是不均勻的)。 我也嘗試過在next()方法中實現它,但是沒有成功。
請給我一個提示,進一步嘗試。
///稍后編輯:我沒有提到要過濾的鏈表由隨機數組成並且未排序。
您的過濾器應位於.next
方法內,而不是.hasNext
。 這是簡單的邏輯:您遍歷整個列表, hasNext
必須始終返回true
,除非當前元素是最后一個元素。
編輯:如果您只需要奇數個數據點,這應該是這樣做的方法。 我認為我們假設您要從奇數索引開始。
@Override
public Integer next() {
//keep looking for an odd element as long as there is a next
while (hasNext()) {
//move to the next node
nextNode = nextNode.next_;
//check for an odd data point
if (nextNode.data_ % 2 == 1) {
//and return it
return data;
}
}
//no odd element was found
throw new NoSuchElementException();
}
您必須使用nextnode.next_兩次才能僅獲得奇數。 這是因為您要跳過nextnode.next_,因為如果當前數字為奇數,則該數字始終為偶數。 此外,您的hasnext需要檢查兩個空格
我們應該看看Iterator.hasNext
和Iterator.next
的官方文檔
http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
對於hasNext
我們閱讀
如果迭代中包含更多元素,則返回true
內部結構無關緊要。 因此,我們別無選擇,我們的實現必須檢查整個鏈接列表,直到找到一個奇數元素或列表的末尾。 另請注意,調用hasNext
不應更改您的結構。
public boolean hasNext() {
Node tempNode = nextNode; // nextNode need to stay the same
while (tempNode != null){
if (tempNode .data_ % 2 != 0){
return true;
}
tempNode = tempNode._next;
}
// if we are here, we found no element that is odd
return false;
}
現在next
方法幾乎相同,這一次我們需要推進內部的nextNode
。 如果我們做不到,則調用者將始終獲得相同的元素。
public Integer next() {
while (nextNode != null){
int data = nextNode.data;
nextNode = nextNode.next_;
if (data % 2 != 0){
return data;
}
}
//no odd element was found
throw new NoSuchElementException();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.