Created
February 15, 2011 15:04
-
-
Save anonymous/827619 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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