LinkedStack.h
#ifndef LINKEDSTACK_H
#define LINKEDSTACK_H
#include<iostream>
//Stack node
template<typename T>
struct stack_node{
typedef stack_node<T>* pointer;
T data;
pointer next;
stack_node() :next(NULL){}
stack_node(const T value) :data(value), next(NULL){}
};
// LinkedStack
template<typename T>
class LinkedStack{
public:
typedef T value_type;
typedef T* pointer;
typedef value_type& reference;
typedef stack_node<T>* link_type;
LinkedStack();//constructor
~LinkedStack();//destructor
void push(const T value);//push
void pop();//pop
reference get_top();//top
bool empty();//whether LinkedStack is empty or not
int size();//get length
private:
void clear();//clear LinkedStack
private:
link_type top;
};
//constructor
template<typename T>
LinkedStack<T>::LinkedStack():top(NULL){}
//destructor
template<typename T>
LinkedStack<T>::~LinkedStack(){
clear();
}
//push
template<typename T>
void LinkedStack<T>::push(const T value){
link_type p = new stack_node<T>(value);
p->next = top;
top = p;
}
//pop
template<typename T>
void LinkedStack<T>::pop(){
if (empty()){
std::cout << "there is no element in stack" << std::endl;
exit(1);
}
link_type p = top;
top = top->next;
delete p;
}
//top
template<typename T>
typename LinkedStack<T>::reference LinkedStack<T>::get_top(){
if (empty()){
std::cout << "there is no element in stack" << std::endl;
exit(1);
}
return top->data;
}
//whether stack is empty or not
template<typename T>
bool LinkedStack<T>::empty(){
return top == NULL ? true : false;
}
//get length
template<typename T>
int LinkedStack<T>::size(){
int count = 0;
link_type p = top;
while (p!=NULL){
p = p->next;
count++;
}
return count;
}
//clear LinkedStack
template<typename T>
void LinkedStack<T>::clear(){
link_type p;
while (top != NULL){
p = top;
top = top->next;
delete p;
}
}
#endif
main.cpp
#include"LinkedStack.h"
using namespace std;
int main(){
LinkedStack<int> int_stack;
cout << int_stack.size() << endl; //0
cout << boolalpha << int_stack.empty() << endl;//true
int_stack.push(1);
cout << int_stack.size() << endl; //1
cout << int_stack.get_top() << endl;//1
int_stack.pop();
for (int i = 0; i < 20; i++){
int_stack.push(i);
}
cout << int_stack.size() << endl; //20
cout << int_stack.get_top() << endl;//19
cout << boolalpha << int_stack.empty() << endl;//false
int_stack.push(21);
cout << int_stack.get_top() << endl;//21
int_stack.pop();
cout << int_stack.get_top() << endl;//19
int_stack.pop();
int_stack.push(22);
cout << int_stack.size() << endl; //20
cout << int_stack.get_top() << endl;//22
int_stack.pop();
cout << int_stack.get_top() << endl;//18
return 0;
}