[ create a new paste ] login | about

Link: http://codepad.org/l1dSVeCQ    [ raw code | output | fork ]

ninwa - C++, pasted on Nov 20:
// Simple stack implementation
#include <iostream>
using namespace std;

template< typename T >
class node
{
public:
	node<T> *next;
	node<T> *prev;

	T data;

	node(node<T> *n = NULL, node<T> *p = NULL){next = n; prev = p;}
	node(T data, node<T> *n = NULL, node<T> *p = NULL ){ 
		this->data = data; 
		next = n;
		prev = p;
	}

	~node()
	{
	}
};

template< typename T >
class nstack
{
private:
	node<T> *top;
	node<T> *bottom;
public:

	unsigned size(){ 
		if( bottom == NULL )
			return 0;

		node<T> *p = top;
		unsigned counter = 0;
		while( p != bottom ){
			counter++;
			p = p->prev;
		}

		return counter;
	}

	T pop()
	{
		T t = top->data;
		node<T> *p = top;
		top = top->prev;
		top->next = NULL;

		delete p;

		return t;
	}

	void push(T data)
	{
		if( bottom == NULL ){
			bottom = new node<T>(data);
			top = bottom;
		}
		else
		{
			top->next = new node<T>(data, NULL, top);
			top = top->next;
		}
	}

	nstack()
	{
		this->top = NULL;
		this->bottom = NULL;
	}

	~nstack()
	{
		node<T> *p = bottom;
		while( p != NULL )
		{
			node<T> *dp = p;
			p = p->next;
			delete dp;
		}
	}
};

int main()
{
	nstack<int> s;
	s.push(3);
	s.push(4);

	cout << s.pop() << endl;
	return 0;
}


Output:
1
4


Create a new paste based on this one


Comments: