#pragma once


#include <iostream>


template <typename T>

class Stack

{

protected:

struct Node

{

T data;

Node *prev; // has been pushed

Node *next; // will be pushed

};

typedef Node* NodePtr;


private:

NodePtr top_;

NodePtr bottom_;

int size_ = -1;


public:

Stack();

virtual ~Stack();


void push(const T&);

void pop();

T& top();

//T& bottom();

const T top() const;

//const T bottom() const;


int isSize() const;

bool isEmpty() const;


public:

friend std::ostream& operator << (std::ostream& os, const Stack& s)

{

NodePtr node = s.bottom_;


while (node != NULL) {

os << node->data << " ";

node = node->next;

}


return os;

}

};


template <typename T>

Stack<T>::Stack()

: top_(NULL), bottom_(NULL), size_(0)

{}


template <typename T>

Stack<T>::~Stack()

{

while (size_ > 0) {

pop();

}

}


template <typename T>

void Stack<T>::push(const T& data)

{

NodePtr new_node = new Node;

new_node->data = data;

new_node->prev = top_;

new_node->next = NULL;


if (isEmpty() == true) {

bottom_ = new_node;

else {

top_->next = new_node;

}


top_ = new_node;


++size_;


}


template <typename T>

void Stack<T>::pop()

{

NodePtr node = top_;


if (size_ == 0) {

std::cout << "Stack is Emtpy" << std::endl;

return;

}


top_ = top_->prev;

if (top_ == NULL) {

bottom_ = NULL;

}

else {

top_->next = NULL;

}


--size_;


delete node;

}


template <typename T>

T& Stack<T>::top()

{

return top_->data;

}


template <typename T>

const T Stack<T>::top() const

{

return top_->data;

}


//template <typename T>

//T& Stack<T>::bottom()

//{

// return back_->data;

//}

//

//template <typename T>

//const T Stack<T>::bottom() const

//{

// return back_->data;

//}


template <typename T>

int Stack<T>::isSize() const

{

return size_;

}


template <typename T>

bool Stack<T>::isEmpty() const

{

return (size_ == 0);

}

'Programming > C,C++' 카테고리의 다른 글

C++, const with function [펌]  (0) 2017.04.07
C, const vs 가변인자 [펌]  (0) 2017.04.07
Queue (Double Linked), C++  (0) 2017.04.06
new delete + Heap overruns checker  (0) 2017.04.05
c++ new delete overriding / leak checker  (0) 2017.04.03
Posted by 루나s
,