Last active
June 16, 2017 05:20
-
-
Save yokolet/e9f1387f213e872d15697d5d13eaedcd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class NestedListIterator implements Iterator<Integer> { | |
interface NestedInteger { | |
boolean isInteger(); | |
Integer getInteger(); | |
List<NestedInteger> getList(); | |
} | |
Stack<Iterator<NestedInteger>> stack; | |
Integer current = null; | |
void updateIterator() { | |
while (!stack.isEmpty() && current == null) { | |
Iterator<NestedInteger> top = stack.peek(); | |
if (!top.hasNext()) { | |
stack.pop(); | |
continue; | |
} | |
NestedInteger ni = top.next(); | |
if (ni.isInteger()) { | |
current = ni.getInteger(); | |
} else { | |
stack.push(ni.getList().iterator()); | |
} | |
} | |
} | |
NestedListIterator(List<NestedInteger> nestedList) { | |
stack = new Stack(); | |
stack.push(nestedList.iterator()); | |
updateIterator(); | |
} | |
@Override | |
public boolean hasNext() { | |
return current != null ? true : false; | |
} | |
@Override | |
public Integer next() { | |
Integer temp = current; | |
current = null; | |
updateIterator(); | |
return temp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment