Skip to content

Commit add6a8d

Browse files
authored
Create 281. Zigzag Iterator.java
1 parent 11285e5 commit add6a8d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

281. Zigzag Iterator.java

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
public class ZigzagIterator {
2+
int index;
3+
int length;
4+
List<Integer> zzList;
5+
public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
6+
zzList = new ArrayList<Integer>();
7+
index = 0;
8+
length = v1.size() + v2.size();
9+
10+
while (index < length) {
11+
if (index % 2 == 0) {
12+
if (v1.size() > 0) {
13+
zzList.add(v1.remove(0));
14+
} else {
15+
zzList.add(v2.remove(0));
16+
}
17+
} else {
18+
if (v2.size() > 0) {
19+
zzList.add(v2.remove(0));
20+
} else {
21+
zzList.add(v1.remove(0));
22+
}
23+
}
24+
index++;
25+
}
26+
index = 0;
27+
}
28+
29+
public int next() {
30+
return zzList.get(index++);
31+
}
32+
33+
public boolean hasNext() {
34+
return index < length;
35+
}
36+
}
37+
38+
/**
39+
* Your ZigzagIterator object will be instantiated and called as such:
40+
* ZigzagIterator i = new ZigzagIterator(v1, v2);
41+
* while (i.hasNext()) v[f()] = i.next();
42+
*/

0 commit comments

Comments
 (0)