Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
template <class T>
class Stack
{
  public:
  Stack(int = 10) ;
  ~Stack() { delete [] stackPtr ; }
  int push(const T&);
  int pop(T&) ;
  int isEmpty()const { return top == -1 ; }
  int isFull() const { return top == size - 1 ; }
private:
  int size ;  // elementtien määrä pinossa
  int top ;
  T* stackPtr ;
} ;

//muodostin
template <class T>
Stack<T>::Stack(int s)
{
	size = s > 0 && s < 1000 ? s : 10 ;
	top = -1 ;  // initialize stack
	stackPtr = new T[size] ;
}

 // uusi arvo pinoon
template <class T>
int Stack<T>::push(const T& item)
{
	if (!isFull())
	{
		stackPtr[++top] = item ;
		return 1 ;  // pinon täytö ok
        }
	return 0 ;  // ei mahdu enaa
}

// elementti pinosta
template <class T>
int Stack<T>::pop(T& popValue)
{
	if (!isEmpty())
	{
		popValue = stackPtr[top--] ;
		return 1 ;  // ok
	}
	return 0 ;  // ei onnistu, pino on tyhja
}

Esimerkki pinon käytöstä

Code Block
#include &ltiostream>
#include "stack.h"
using namespace std ;
void main()
{
	Stack <float> FloatStack ;
	Stack <int> IntStack ;

	FloatStack fs(5) ;
	float f = 1.1 ;
	cout << "laitetaan luku reaalilukupinoon fs" << endl ;
	while (fs.push(f))
	{
		cout << f << ' ' ;
		f += 1.1 ;
	}
	cout << endl << "Pino täynnä." << endl
	<< endl << "Otetaan elementi pinosta" << endl ;
	while (fs.pop(f))
		cout << f << ' ' ;
	cout << endl << "pino tyhjä" << endl ;
	cout << endl ;

	IntStack is ;
	int i = 1.1 ;
	cout << "laitetaan luku kokonaislukupinoon" << endl ;
	while (is.push(i))
	{
		cout << i << ' ' ;
		i += 1 ;
	}
	cout << endl << "pino täynnä" << endl
	<< endl << "otetaan elementti pinosta" << endl ;
	while (is.pop(i))
			cout << i << ' ' ;
	cout << endl << "pino tyhjä" << endl ;
}