Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Zigzag Iterator in C++
Suppose there are two 1D arrays, we have to implement an iterator that will return their elements alternately. There will be two methods −
next() − to get next element
hasNext() − to check whether the next element is present or not.
So, if the input is like v1 = [1,2] v2 = [3,4,5,6] , then the output will be [1,3,2,4,5,6],
To solve this, we will follow these steps −
Define one queue q of pairs
From the initializer ake two arrays v1 and v2,
-
if size of v1, then −
insert { 0, 0 } into q
-
if size of v2, then −
insert { 0, 1 } into q
Define one pair temp
temp := first element of q
delete element from q
ret := 0
-
if temp.second is same as 1, then −
ret := v2[temp.first]
(increase temp.first by 1)
-
if temp.first < size of v2, then −
insert temp into q
-
Otherwise
ret := v1[temp.first]
(increase temp.first by 1)
-
if temp.first < size of v1, then −
insert temp into q
return ret
Define a function hasNext()
return true when q is not empty
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h>
using namespace std;
class ZigzagIterator {
public:
queue <pair<int, int>> q;
vector <int< v1, v2;
ZigzagIterator(vector<int<& v1, vector<int<& v2) {
this->v1 = v1;
this->v2 = v2;
if (v1.size()) {
q.push({ 0, 0 });
}
if (v2.size()) {
q.push({ 0, 1 });
}
}
int next() {
pair<int, int> temp;
temp = q.front();
q.pop();
int ret = 0;
if (temp.second == 1) {
ret = v2[temp.first];
temp.first++;
if (temp.first < v2.size())
q.push(temp);
}
else {
ret = v1[temp.first];
temp.first++;
if (temp.first < v1.size())
q.push(temp);
}
return ret;
}
bool hasNext() {
return !q.empty();
}
};
main(){
vector<int< v1 = {1,3,5,7}, v2 = {2,4,6,8,10,12,17};
ZigzagIterator ob(v1, v2);
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.hasNext() ? "True" : "False") << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.hasNext() ? "True" : "False") << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.hasNext() ? "True" : "False") << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.hasNext() ? "True" : "False") << endl;
}
Input
{1,3,5,7},{2,4,6,8,10,12,17}
Output
1 2 True 3 4 5 True 6 7 8 10 True 12 17 False