From 2836fceedc29519362f2e75c4a057abc75aa4955 Mon Sep 17 00:00:00 2001 From: Valentin Gehrke Date: Wed, 11 Nov 2015 12:34:18 +0100 Subject: [PATCH] List mit 3 arrays --- list.cpp | 142 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 list.cpp diff --git a/list.cpp b/list.cpp new file mode 100644 index 0000000..bb33698 --- /dev/null +++ b/list.cpp @@ -0,0 +1,142 @@ +#include +#include + +using namespace std; + +template +class List { + private: + T* data; + int* next; + int* free; + int head; + int current; + int size; + int next_free; + public: + List(int size); + bool insert(T e); + bool remove(); + bool find_first(); + bool find_next(); + bool find_prior(); + bool full(); + bool empty(); + T retrieve(); + void update(T e); +}; + +template +List::List(int size) : size(size), head(-1), current(-1), next_free(size-1) { + this->data = new T[size]; + this->next = new int[size]; + this->free = new int[size]; + for(int i = 0; i < size; i++) { + this->next[i] = -1; + this->free[i] = i; + } +} + +template +bool List::full() { + return (this->next_free == -1); +} + +template +bool List::empty() { + return (this->head == -1); +} + +template +bool List::insert(T e) { + if(this->full()) return false; + int p = this->free[next_free--]; + this->data[p] = e; + if(this->empty()) { + this->head = p; + } else { + this->next[p] = this->next[this->current]; + this->next[this->current] = p; + } + this->current = p; + return true; +} + +template +bool List::find_prior() { + if(this->empty()) return false; + int p = this->head; + while(p!=-1 && this->next[p] != this->current) { + p = this->next[p]; + } + if(p == -1) { + return false; + } else { + this->current = p; + return true; + } +} + +template +bool List::remove() { + if(this->empty()) return false; + int node_rem = this->current; + if(node_rem == this->head) { + this->head = this->next[node_rem]; + this->current = this->head; + } else { + assert(this->find_prior()); + this->next[this->current] = this->next[node_rem]; + } + this->next[node_rem] = -1; + this->free[++this->next_free] = node_rem; + return true; +} + +template +bool List::find_next() { + if(this->empty()) return false; + if(this->next[this->current] == -1) return false; + this->current = this->next[this->current]; + return true; +} + +template +bool List::find_first() { + if(this->empty()) return false; + this->current = this->head; + return true; +} + +template +T List::retrieve() { + assert(!this->empty()); + return this->data[current]; +} + +template +void List::update(T e) { + assert(!this->empty()); + this->data[current] = e; +} + +int main( int argc, char *argv[] ) { + List l(20); + int i; + for(i = 0; !l.full(); i++) { + l.insert(i); + } + assert(i == 20); + assert(l.find_first()); + while(l.find_next()) { + cout << l.retrieve() << endl; + } + + assert(l.find_first()); + while(!l.empty()) l.remove(); + + + assert(!l.find_first()); + + return 0; +}