// Given an iterator with methods next() and hasNext(), create a wrapper iterator, PeekableInterface,
// which also implements peek(). peek shows the next element that would be returned on next().
// Here is the interface (This problem was written with Python in mind but I adapted it to C++):
//
// class PeekableInterface(object) :
// def __init__(self, iterator) :
// pass
//
// def peek(self) :
// pass
//
// def next(self) :
// pass
//
// def hasNext(self) :
// pass
#include <iostream>
#include <string>
#include <exception>
using namespace std;
class MyIterator
{
private:
MyIterator* nextIt = nullptr;
int data;
public:
MyIterator(MyIterator* nextPtr = nullptr)
{
nextIt = nextPtr;
}
int getData() { return data; }
void setData(int newData) { data = newData; }
void setNextIt(MyIterator* nxt) { nextIt = nxt; }
bool hasNext() { return nextIt != nullptr; }
int next() { return nextIt->getData(); }
};
struct NoNextException : public exception
{
const char * what() const throw ()
{
return "Trying to read next value that doesn't exist";
}
};
class PeekableInterface : public MyIterator
{
public:
PeekableInterface(PeekableInterface* nextPtr = nullptr) { this->setNextIt(nextPtr); }
int peek()
{
try {
if (this->hasNext())
return this->next();
else
throw NoNextException();
}
catch (NoNextException& e) { cout << e.what() << endl; return 0; }
}
};
int main()
{
PeekableInterface* it = new PeekableInterface();
it->setData(1);
PeekableInterface* it2 = new PeekableInterface(it);
it2->setData(2);
PeekableInterface* it3 = new PeekableInterface(it2);
it3->setData(3);
cout << it3->peek() << endl;
cout << it3->next() << endl;
cout << it2->peek() << endl;
cout << it->peek() << endl;
// cout << it->next() << endl; // this hould cause the program to crash because we are getting a next() when there isnt one
return 0;
}
Comments