2018-02-24 03:19:29 +00:00
|
|
|
#ifndef __KF_STACK_H__
|
|
|
|
#define __KF_STACK_H__
|
|
|
|
|
|
|
|
#include "defs.h"
|
|
|
|
|
|
|
|
template <typename T>
|
|
|
|
class Stack {
|
|
|
|
public:
|
|
|
|
bool push(T val);
|
2018-02-25 06:35:58 +00:00
|
|
|
bool pop(T *val);
|
2018-03-02 00:09:06 +00:00
|
|
|
bool peek(T *val);
|
2018-02-24 03:19:29 +00:00
|
|
|
bool get(size_t, T &);
|
2018-02-28 03:59:29 +00:00
|
|
|
bool remove(size_t, T *);
|
2018-02-25 06:35:58 +00:00
|
|
|
size_t size(void) { return this->arrlen; }
|
|
|
|
void clear(void) { this->arrlen = 0; }
|
2018-02-24 03:19:29 +00:00
|
|
|
private:
|
|
|
|
T arr[STACK_SIZE];
|
|
|
|
size_t arrlen;
|
|
|
|
};
|
|
|
|
|
|
|
|
// push returns false if there was a stack overflow.
|
|
|
|
template <typename T>
|
|
|
|
bool
|
|
|
|
Stack<T>::push(T val)
|
|
|
|
{
|
|
|
|
if ((this->arrlen + 1) > STACK_SIZE) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
this->arr[this->arrlen++] = val;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// pop returns false if there was a stack underflow.
|
|
|
|
template <typename T>
|
|
|
|
bool
|
2018-02-25 06:35:58 +00:00
|
|
|
Stack<T>::pop(T *val)
|
2018-02-24 03:19:29 +00:00
|
|
|
{
|
|
|
|
if (this->arrlen == 0) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2018-02-25 06:35:58 +00:00
|
|
|
*val = this->arr[this->arrlen - 1];
|
2018-02-24 03:19:29 +00:00
|
|
|
this->arrlen--;
|
2018-02-25 06:35:58 +00:00
|
|
|
return true;
|
2018-02-24 03:19:29 +00:00
|
|
|
}
|
|
|
|
|
2018-03-02 00:09:06 +00:00
|
|
|
// peek returns false if there was a stack underflow.
|
|
|
|
template <typename T>
|
|
|
|
bool
|
|
|
|
Stack<T>::peek(T *val)
|
|
|
|
{
|
|
|
|
if (this->arrlen == 0) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
*val = this->arr[this->arrlen - 1];
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2018-02-24 03:19:29 +00:00
|
|
|
// get returns false on invalid bounds.
|
|
|
|
template <typename T>
|
|
|
|
bool
|
|
|
|
Stack<T>::get(size_t i, T &val)
|
|
|
|
{
|
|
|
|
if (i > this->arrlen) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
val = this->arr[i];
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2018-02-28 03:59:29 +00:00
|
|
|
// remove returns false on invalid bounds
|
|
|
|
template <typename T>
|
|
|
|
bool
|
|
|
|
Stack<T>::remove(size_t i, T *val)
|
|
|
|
{
|
|
|
|
if (i > this->arrlen) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
*val = this->arr[i];
|
|
|
|
for (; i < (arrlen - 1); i++) {
|
|
|
|
this->arr[i] = this->arr[i+1];
|
|
|
|
}
|
|
|
|
arrlen--;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2018-02-24 03:19:29 +00:00
|
|
|
#endif // __KF_STACK_H__
|