Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit4e3224d

Browse files
authored
Update Flatten Nested List Iterator.java
1 parentc10ed38 commit4e3224d

File tree

1 file changed

+20
-33
lines changed

1 file changed

+20
-33
lines changed

‎Medium/Flatten Nested List Iterator.java

Lines changed: 20 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -11,52 +11,39 @@
1111
* public Integer getInteger();
1212
*
1313
* // @return the nested list that this NestedInteger holds, if it holds a nested list
14-
* // Returnnull if this NestedInteger holds a single integer
14+
* // Returnempty list if this NestedInteger holds a single integer
1515
* public List<NestedInteger> getList();
1616
* }
1717
*/
1818
publicclassNestedIteratorimplementsIterator<Integer> {
19-
List<NestedInteger>nestedList;
20-
Queue<Integer>queue;
21-
intidx;
19+
20+
privateStack<NestedInteger>stack;
21+
2222
publicNestedIterator(List<NestedInteger>nestedList) {
23-
this.nestedList =nestedList;
24-
queue =newLinkedList<>();
25-
idx =0;
26-
addToQueue();
23+
stack =newStack<>();
24+
for (inti =nestedList.size() -1;i >=0;i--) {
25+
stack.push(nestedList.get(i));
26+
}
2727
}
2828

2929
@Override
3030
publicIntegernext() {
31-
intval =queue.remove();
32-
if (queue.isEmpty()) {
33-
if (idx !=nestedList.size()) {
34-
addToQueue();
35-
}
36-
}
37-
returnval;
38-
}
39-
40-
privatevoidaddToQueue() {
41-
while (idx <nestedList.size() &&queue.isEmpty()) {
42-
addToQueueHelper(nestedList.get(idx++));
43-
}
31+
returnstack.pop().getInteger();
4432
}
4533

46-
privatevoidaddToQueueHelper(NestedIntegerns) {
47-
if (ns.isInteger()) {
48-
queue.add(ns.getInteger());
49-
}
50-
else {
51-
for (NestedIntegerni :ns.getList()) {
52-
addToQueueHelper(ni);
53-
}
54-
}
55-
}
56-
5734
@Override
5835
publicbooleanhasNext() {
59-
return !(queue.isEmpty() &&idx ==nestedList.size());
36+
while (!stack.isEmpty() && !stack.peek().isInteger()) {
37+
NestedIntegerpopped =stack.pop();
38+
if (popped ==null) {
39+
continue;
40+
}
41+
List<NestedInteger>list =popped.getList();
42+
for (inti =list.size() -1;i >=0;i--) {
43+
stack.push(list.get(i));
44+
}
45+
}
46+
return !stack.isEmpty();
6047
}
6148
}
6249

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp