#ifndef STACK_H
#define STACK_H
template<class T>
class MyStack
{
private:
struct Node
{
T elem;
struct Node* next;
};
struct Node* getNewNode(T e)const;
struct Node* head;
public:
void push(T elem);
Node* pop();
bool IsEmpty() const;
MyStack();
};
#endif // STACK_H
#include "stack.h"
#include<iostream>
template<class T>
MyStack<T>::MyStack()
{
head=nullptr;
}
template<class T>
void MyStack<T>::push(T elem)
{
typename MyStack<T>::Node* node=getNewNode(elem);
node->next=head;
head=node;
}
template<class T>
typename MyStack<T>::Node* MyStack<T>::getNewNode(T e)const
{
typename MyStack<T>::Node* newNode=nullptr;
try{
newNode= new typename MyStack<T>::Node ;
}catch (const std::bad_alloc& e) {
std::cout << "Allocation failed: " << e.what() << '\n';
}
newNode->data=e;
newNode->next=nullptr;
return newNode;
}
template<class T>
typename MyStack<T>::Node* MyStack<T>::pop()
{
if(!IsEmpty())
{
std::cout<<"Stack is empty\n";
}
else
{
typename MyStack<T>::Node* temp=head;
head=head->next;
return temp;
}
}
template<class T>
bool MyStack<T>::IsEmpty() const
{
return (head)?true:false;
}
int main()
{
MyStack<int> a;
a.push(11);
a.push(12);
a.push(13);
std::cout<<"POPED Val "<<a.pop()->elem<<"\n";
std::cout<<"POPED Val "<<a.pop()->elem<<"\n";
std::cout<<"POPED Val "<<a.pop()->elem<<"\n";
std::cout<<"POPED Val "<<a.pop()->elem<<"\n";
std::cout<<"POPED Val "<<a.pop()->elem<<"\n";
}
No comments:
Post a Comment