Skip to content

Instantly share code, notes, and snippets.

Created February 15, 2011 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/827619 to your computer and use it in GitHub Desktop.
Save anonymous/827619 to your computer and use it in GitHub Desktop.
#include <iostream>
struct Point
{
double x, y, z;
Point* next;
};
// WARNING: not thread safe
template <typename T> class InStack
{
private:
T* stack;
public:
InStack () : stack(0) {}
~InStack ()
{
clear();
}
void push (T* item)
{
item->next = stack;
stack = item;
}
T* pop ()
{
T* temp = stack;
stack = stack->next;
return temp;
}
void clear ()
{
while (stack)
{
T* temp = stack;
stack = stack->next;
delete temp; // Can we assume that new was always used?
}
}
T* top ()
{
return stack;
}
T* next (T* item)
{
return item ? item->next : 0;
}
unsigned getLength ()
{
unsigned length = 0;
T* temp = stack;
while (temp)
{
++length;
temp = temp->next;
}
return length;
}
};
int main(int argc, char *argv[])
{
InStack<Point> stack;
Point* a = new Point;
Point* b = new Point;
Point* c = new Point;
a->x = 10;
b->x = 20;
c->x = 30;
stack.push(&a);
stack.push(&b);
stack.push(&c);
std::cout << "Length: " << stack.getLength() << "\n";
std::cout << "Top: " << stack.top()->x << "\n";
std::cout << "next: " << stack.next(stack.top())->x << "\n";
std::cout << "null.next: " << stack.next(0) << "\n";
std::cout << "pop: " << stack.pop()->x << "\n";
std::cout << "pop: " << stack.pop()->x << "\n";
std::cout << "Length: " << stack.getLength() << "\n";
stack.push(&c);
std::cout << "Top: " << stack.top()->x << "\n";
std::cout << "Length: " << stack.getLength() << "\n";
stack.clear();
std::cout << "Length: " << stack.getLength() << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment