lc281

281-ZigzagIterator

Description
Given two vectors of integers v1 and v2, implement an iterator to return their elements alternately.

Implement the ZigzagIterator class:

  • ZigzagIterator(List v1, List v2) initializes the object with the two vectors v1 and v2.
  • boolean hasNext() returns true if the iterator still has elements, and false otherwise.
  • int next() returns the current element of the iterator and moves the iterator to the next element.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
Input
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 2, 2, false]

Explanation
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class ZigzagIterator {
private:
queue<int> q;
public:

ZigzagIterator(vector<int>& v1, vector<int>& v2) {
int idx = 0;
while (idx < v1.size() || idx < v2.size()) {
if (idx < v1.size()) q.push(v1[idx]);
if (idx < v2.size()) q.push(v2[idx]);

idx++;
}

}

int next() {
int x = q.front();
q.pop();
return x;
}

bool hasNext() {
return !q.empty();
}
};

/**
* Your ZigzagIterator object will be instantiated and called as such:
* ZigzagIterator i(v1, v2);
* while (i.hasNext()) cout << i.next();
*/
Author

Joe Chu

Posted on

2023-11-06

Updated on

2024-03-24

Licensed under

Comments