#341
Medium Algorithms Flatten nested list iterator
Stack Tree Depth-First Search Design Queue Iterator
65.6% acceptance
Jan 12, 2026
5065
1795
You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the NestedIterator class:
NestedIterator(List nestedList) Initializes the iterator with the nested list nestedList.
int next() Returns the next integer in the nested list.
boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.
Your code will be tested with the following pseudocode:
initialize iterator with nestedList
res = []
while iterator.hasNext()
append iterator.next() to the end of res
return res
If res matches the expected flattened list, then your code will be judged as correct.
Solution
Rust
Time O(2^n)
Space O(n)
#[derive(Debug, PartialEq, Eq)]
pub enum NestedInteger {
Int(i32),
List(Vec<NestedInteger>),
}
/*
* struct NestedIterator {
* }
* /**
* * `&self` means the method takes an immutable reference.
* * If you need a mutable reference, change it to `&mut self` instead.
* */
* impl NestedIterator {
* fn new(nestedList: Vec<NestedInteger>) -> Self {
* }
* fn next(&self) -> i32 {
* }
* fn has_next(&self) -> bool {
* }
* }
*/
struct NestedIterator {
nums: std::cell::RefCell<Vec<i32>>,
index: std::cell::RefCell<usize>,
}
impl NestedIterator {
fn new(nested_list: Vec<NestedInteger>) -> Self {
let mut nums = Vec::new();
Self::flatten(&nested_list, &mut nums);
NestedIterator {
nums: std::cell::RefCell::new(nums),
index: std::cell::RefCell::new(0),
}
}
fn flatten(nested_list: &[NestedInteger], nums: &mut Vec<i32>) {
for item in nested_list {
match item {
NestedInteger::Int(val) => nums.push(*val),
NestedInteger::List(list) => Self::flatten(list, nums),
}
}
}
fn next(&self) -> i32 {
let mut index = self.index.borrow_mut();
let nums = self.nums.borrow();
let val = nums[*index];
*index += 1;
val
}
fn has_next(&self) -> bool {
let index = self.index.borrow();
let nums = self.nums.borrow();
*index < nums.len()
}
}
/*
* Your NestedIterator object will be instantiated and called as such:
* let obj = NestedIterator::new(nestedList);
* let ret_1: i32 = obj.next();
* let ret_2: bool = obj.has_next();
*/