Yahoo Interview Question
Software Engineer / DevelopersTeam: Ad
Country: United States
Interview Type: In-Person
public class IteratorToSkipZero {
int current;
int[] list;
public static void main(String[] args) {
int[] input = {1,0,0,0,0,6,0};
IteratorToSkipZero it = new IteratorToSkipZero(input);
System.out.println(it.next());
System.out.println(it.next());
System.out.println(it.hasNext());
}
public IteratorToSkipZero(int[] l){
list = l;
current = 0;
}
public boolean hasNext(){
skipZero();
if(current == (list.length)){
return false;
}
return true;
}
public int next(){
int o = 0;
if(hasNext()){
o = list[current];
current++;
return o;
}
throw new UnsupportedOperationException();
}
private void skipZero() {
while(current < list.length){
if(list[current] == 0){
current ++;
} else {
break;
}
}
}
}
package com.test.integer;
public class GreaterThanZeroIntIterator {
private int[] intValues;
private int curIndex = 0;
private boolean hasNext = false;
public GreaterThanZeroIntIterator(int[] intValues) {
super();
this.intValues = intValues;
fetchNext();
}
public static void main(String[] args) {
int[] intArr = new int[] { 1, 2, 3, 0, 1, 2, -3 };
GreaterThanZeroIntIterator it = new GreaterThanZeroIntIterator(intArr);
while (it.hasNext()) {
System.out.println(it.next());
}
}
public boolean hasNext() {
return hasNext;
}
public int next() {
int result = intValues[curIndex++];
fetchNext();
return result;
}
private void fetchNext() {
hasNext = false;
while (curIndex < intValues.length) {
if (intValues[curIndex] != 0) {
hasNext = true;
break;
} else {
curIndex++;
}
}
}
}
public class IntegerStream implements Iterable{
private Node head;
@Override
public Iterator iterator() {
return null;
}
class Node{
private Integer data;
private Node next;
}
class IntegerStreamIterator implements Iterator {
Node curr = head;
@Override
public boolean hasNext() {
return curr != null;
}
@Override
public Object next() {
while(curr.data == 0){
curr = curr.next;
}
Integer item = curr.data;
curr = curr.next;
return item;
}
}
}
explain what iterator is in algorithms?
- Anonymous March 20, 2014