Data Structure Using C++
Stack Data Structure
Stack Template
int arr[12]={31,29,31,30,31,30,31,31,30,31,30,31};
template <class t>
class node
{
private:
t data;
node<t> *next;
public:
node(t d);
void setData (t d);
t getData ();
void setNext (node<t> *);
node<t>* getNext ();
void showData();
};
template <class t>
node<t>::node(t d)
{
data=d;
next=NULL;
}
template <class t>
void node<t>::setData (t d)
{
data=d;
}
template <class t>
t node<t>::getData()
{
return data;
}
template <class t>
void node<t>::setNext (node<t> *ptr)
{
next=ptr;
}
template <class t>
node<t> * node<t>::getNext()
{
return next;
}
template <class t>
void node<t>::showData()
{
cout<<getData()<<" ";
}
template <class t>
class stack
{
private:
node<t> *head;
public:
stack();
void push(t val);
t pop ();
t topElement();
int isEmpty ();
};
template <class t>
stack<t>::stack()
{
head=NULL;
}
template <class t>
void stack<t>::push(t val)
{
node<t> *ptr= new node<t> (val);
ptr->setNext(head);
head=ptr;
}
template <class t>
t stack<t>::pop()
{
if(isEmpty())
{
cout<<"Error: Stack is empty. can't pop element."<<endl;
}
else
{
t val=head->getData();
head=head->getNext();
return val;
}
}
template <class t>
t stack<t>::topElement()
{
return head->getData();
}
template <class t>
int stack<t>::isEmpty()
{
return head==NULL;
}
class Date
{
private:
int day;
int month;
int year;
public:
Date(int=1, int=1, int=1900);
void setDate(int, int, int);
void showDate() const;
};
Date::Date(int d, int m, int y)
{
setDate(d,m,y);
}
void Date::setDate(int d, int m, int y)
{
month=((m>=1&&m<=12)?m:1&&cout<<"Invalid month."<<endl);
if((m%4==0&&m%100!=0)||(m%100==0&&m%400==0))
arr[1]=29;
else
arr[1]=28;
day=((d>=1&&d<=arr[month-1])?d:1&&cout<<"Invalid day."<<endl);
year=((y>=1900&&y<=3000)?y:1900&&cout<<"Invalid year."<<endl);
}
void Date::showDate() const
{
cout<<"Date is : "<<day<<"-"<<month<<"-"<<year<<endl;
}
int main ()
{
stack <Date> s;
Date s1;
s1.setDate(3,12,1998);
s.push(s1);
Date s2=s.pop();
cout<<"Popped element is : "<<s2.;
s2.showDate();
}
Let me know in the comment section if you have any question.
Previous Post:
Infix (With Parenthesis) to Postfix Conversion Using Linked List Stack in Data Structure Using C++
Comments
Post a Comment