-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreorder_iterator.cpp
41 lines (38 loc) · 1.22 KB
/
preorder_iterator.cpp
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
33
34
35
36
37
38
39
40
41
#include "iterator.hpp"
#include <iostream>
PreorderIterator::PreorderIterator(Base* ptr) : Iterator(ptr) {
this->iterators = std::stack<Iterator*>();
}
void PreorderIterator::first() {
while(!this->iterators.empty()) {
this->iterators.pop();
}
if(this->self_ptr) {
Iterator* root_itr = this->self_ptr->create_iterator();
root_itr->first();
this->iterators.push(root_itr);
}
}
void PreorderIterator::next() {
// The notes say to create an iterator for the item on the top of the stack, but the stack is
// an iterator so it should probably say create an item for the current of the iterator on the
// top of the stack
Iterator* top_itr = this->iterators.top()->current()->create_iterator();
top_itr->first();
this->iterators.push(top_itr);
while(!this->iterators.empty() && this->iterators.top()->is_done()) {
this->iterators.pop();
if(!this->iterators.empty()) {
this->iterators.top()->next();
}
}
}
bool PreorderIterator::is_done() {
return this->iterators.empty();
}
Base* PreorderIterator::current() {
if(!this->iterators.empty()) {
return this->iterators.top()->current();
}
return nullptr;
}