341. Flatten Nested List Iterator Medium
1/**
2 * [341] Flatten Nested List Iterator
3 *
4 * 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.
5 * Implement the NestedIterator class:
6 *
7 * NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList.
8 * int next() Returns the next integer in the nested list.
9 * boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.
10 *
11 * Your code will be tested with the following pseudocode:
12 *
13 * initialize iterator with nestedList
14 * res = []
15 * while iterator.hasNext()
16 * append iterator.next() to the end of res
17 * return res
18 *
19 * If res matches the expected flattened list, then your code will be judged as correct.
20 *
21 * Example 1:
22 *
23 * Input: nestedList = [[1,1],2,[1,1]]
24 * Output: [1,1,2,1,1]
25 * Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].
26 *
27 * Example 2:
28 *
29 * Input: nestedList = [1,[4,[6]]]
30 * Output: [1,4,6]
31 * Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
32 *
33 *
34 * Constraints:
35 *
36 * 1 <= nestedList.length <= 500
37 * The values of the integers in the nested list is in the range [-10^6, 10^6].
38 *
39 */
40pub struct Solution {}
41
42// problem: https://leetcode.com/problems/flatten-nested-list-iterator/
43// discuss: https://leetcode.com/problems/flatten-nested-list-iterator/discuss/?currentPage=1&orderBy=most_votes&query=
44
45// submission codes start here
46
47// #[derive(Debug, PartialEq, Eq)]
48// pub enum NestedInteger {
49// Int(i32),
50// List(Vec<NestedInteger>)
51// }
52struct NestedIterator {
53 0
54 }
55
56
57/**
58 * `&self` means the method takes an immutable reference.
59 * If you need a mutable reference, change it to `&mut self` instead.
60 */
61impl NestedIterator {
62
63 fn new(nestedList: Vec<NestedInteger>) -> Self {
64
65 }
66
67 fn next(&self) -> i32 {
68
69 }
70
71 fn has_next(&self) -> bool {
72
73 }
74}
75
76/**
77 * Your NestedIterator object will be instantiated and called as such:
78 * let obj = NestedIterator::new(nestedList);
79 * let ret_1: i32 = obj.next();
80 * let ret_2: bool = obj.has_next();
81 */
82
83// submission codes end
84
85#[cfg(test)]
86mod tests {
87 use super::*;
88
89 #[test]
90 fn test_341() {
91 }
92}
93
Back
© 2025 bowen.ge All Rights Reserved.