Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // LeetCode URL: https://leetcode.com/problems/flatten-nested-list-iterator/
- import java.util.Iterator;
- import java.util.List;
- import java.util.NoSuchElementException;
- import java.util.Stack;
- // This is the interface that allows for creating nested lists.
- // You should not implement it, or speculate about its implementation
- interface NestedInteger {
- // @return true if this NestedInteger holds a single integer, rather than a
- // nested list.
- public boolean isInteger();
- // @return the single integer that this NestedInteger holds, if it holds a
- // single integer
- // Return null if this NestedInteger holds a nested list
- public Integer getInteger();
- // @return the nested list that this NestedInteger holds, if it holds a nested
- // list
- // Return null if this NestedInteger holds a single integer
- public List<NestedInteger> getList();
- }
- /**
- * Using stack.
- *
- * Time Complexity: O(N)
- *
- * Space ComplexityL O(N)
- *
- * N = Total length of the nested list.
- */
- class NestedIterator implements Iterator<Integer> {
- Stack<NestedInteger> stack = new Stack<>();
- public NestedIterator(List<NestedInteger> nestedList) {
- if (nestedList == null) {
- return;
- }
- flattenList(nestedList);
- }
- @Override
- public Integer next() throws NoSuchElementException {
- if (!hasNext()) {
- throw new NoSuchElementException("No next element");
- }
- return stack.pop().getInteger();
- }
- @Override
- public boolean hasNext() {
- while (!stack.isEmpty()) {
- if (stack.peek().isInteger()) {
- return true;
- }
- flattenList(stack.pop().getList());
- }
- return false;
- }
- private void flattenList(List<NestedInteger> list) {
- for (int i = list.size() - 1; i >= 0; i--) {
- stack.push(list.get(i));
- }
- }
- }
- // Your NestedIterator object will be instantiated and called as such:
- // NestedIterator i = new NestedIterator(nestedList);
- // while (i.hasNext()) v[f()] = i.next();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement