106 lines
2.6 KiB
C++
Executable File
106 lines
2.6 KiB
C++
Executable File
#pragma once
|
|
#include <iostream>
|
|
|
|
template <class E> class Node {
|
|
private:
|
|
E content;
|
|
Node *nextNode;
|
|
|
|
public:
|
|
Node();
|
|
Node(E _content, Node<E> *_nextNode = NULL);
|
|
~Node();
|
|
// Returns a reference to the content.
|
|
E &getContent();
|
|
// Returns a reference to the next Node. May return NULL if this Node is the
|
|
// last one.
|
|
Node<E> *getNextPtr();
|
|
// Set the next Node _nextNode. Returns original pointer.
|
|
Node<E> *setNext(Node<E> *_nextNode);
|
|
// Returns a reference to the Tail.
|
|
Node<E> &getTail();
|
|
// Returns a reference to the Node of given index.
|
|
Node<E> &getByIndex(const int index);
|
|
// Compare the content with the argument.
|
|
bool operator==(const E &other);
|
|
// Destructs the Node itself and all the node behind it.
|
|
void destruct();
|
|
};
|
|
|
|
template <class E> class Iterator {
|
|
private:
|
|
Node<E> *current;
|
|
|
|
public:
|
|
Iterator(Node<E> *pos);
|
|
bool hasNext();
|
|
// Return the same as hasNext();
|
|
operator bool();
|
|
E &next();
|
|
};
|
|
|
|
template <class E> Node<E>::Node() : content(0), nextNode(NULL){};
|
|
|
|
template <class E>
|
|
Node<E>::Node(E _content, Node *_nextNode)
|
|
: content(_content), nextNode(_nextNode){};
|
|
|
|
template <class E> Node<E>::~Node(){};
|
|
|
|
template <class E> E &Node<E>::getContent() {
|
|
return this->content;
|
|
}
|
|
|
|
template <class E> Node<E> *Node<E>::getNextPtr() {
|
|
return this->nextNode;
|
|
}
|
|
|
|
template <class E> Node<E> *Node<E>::setNext(Node<E> *_nextNode) {
|
|
Node<E> *temp = this->nextNode;
|
|
this->nextNode = _nextNode;
|
|
return temp;
|
|
}
|
|
|
|
template <class E> Node<E> &Node<E>::getTail() {
|
|
if (this->nextNode == NULL) {
|
|
return *this;
|
|
}
|
|
return this->nextNode->getTail();
|
|
}
|
|
|
|
template <class E> Node<E> &Node<E>::getByIndex(const int index) {
|
|
if (index == 0) {
|
|
return *this;
|
|
}
|
|
return this->nextNode->getByIndex(index - 1);
|
|
}
|
|
|
|
template <class E> bool Node<E>::operator==(const E &other) {
|
|
return this->content == other;
|
|
}
|
|
|
|
template <class E> void Node<E>::destruct() {
|
|
if (this->nextNode != NULL) {
|
|
this->nextNode->destruct();
|
|
}
|
|
delete this;
|
|
}
|
|
|
|
template <class E> Iterator<E>::Iterator(Node<E> *start) : current(start){};
|
|
|
|
template <class E> bool Iterator<E>::hasNext() {
|
|
return this->current != NULL;
|
|
}
|
|
|
|
template <class E> Iterator<E>::operator bool() {
|
|
return this->hasNext();
|
|
}
|
|
|
|
template <class E> E &Iterator<E>::next() {
|
|
if (!this->hasNext()) {
|
|
throw(IndexError("Out of bound!"));
|
|
}
|
|
E &temp = this->current->getContent();
|
|
this->current = this->current->getNextPtr();
|
|
return temp;
|
|
} |