C++ example - Stack


C++ example - Stack

This is C++ example code of the Stack data structure.

This is the C++ example code for a stack. A stack can be constructed from a linked list by allowing an item to be added and removed only from the front.

#include <cstdlib>
#include <iostream>
#include <conio.h>
using namespace std;

template <class Type> class List;

template <class Type>
class ListElem {

public:
ListElem (const Type elem){prev=next=0; val=elem;}
public:
Type val; // the element data
ListElem *prev; // previous link
ListElem *next; // next link

};

//---------------------------------------------------------
template <class Type>
class Stack {

public:
Stack(){pfirst=plast=0;}
~Stack();
void push(const Type&);
Type pop();//delete item from the list
void getallval();//print out all items on the screen
int countitem();//return the number of items in the list
protected:
ListElem<Type> *pfirst; // pfirst element in the list
ListElem<Type> *plast; // last element in the list


};

//destructor
template <class Type>
Stack<Type>::~Stack (void)
{

ListElem<Type> *item;
ListElem<Type> *next;
for(item =pfirst; item!= 0; item= next){
next = item->next;
delete item;
}


}
//insert item

template <class Type>
void Stack<Type>::push (const Type &elem)
{

ListElem<Type> *item = new ListElem<Type>(elem);//new element to be inserted

//empty list
if(pfirst==0 && plast==0){
pfirst=item;
plast=item;
}
//insert new item at the beginning of the list
else
{
ListElem<Type> *f;
f=pfirst;
pfirst=item;
pfirst->next=f;
f->prev=pfirst;

   }
}

//Print out all items on the screen

template <class Type>
void Stack<Type>::getallval()
{
if(countitem()>0){
ListElem<Type> *i;
for(i=pfirst;i!=0;i=i->next){
cout<<"\n"<<i->val;

   }
 }
else cout<<"\nNo item found";

}

template <class Type>
int Stack<Type>::countitem()
{

ListElem<Type> *i;
int t=0;
for(i=pfirst;i!=0;i=i->next){
t=t+1;

  }
return t;

}

template <class Type>
Type Stack<Type>::pop(){

Type data;
if(countitem()>0){
ListElem<Type> *temp;

temp=pfirst;
pfirst=pfirst->next;
pfirst->prev=0;
data=temp->val;
delete temp;
return data;


}


}

int main(){

Stack<int> mylist;
mylist.push(30);
mylist.push(20);
mylist.push(24);
mylist.push(25);
mylist.push(200);
mylist.push(205);
cout<<"Remove item="<<mylist.pop()<<endl;
cout<<"Remove item="<<mylist.pop();
cout<<"\nNumber of Items:"<<mylist.countitem()<<"\n";
cout<<"All items:\n";
mylist.getallval();
getch();
return 0;

}




Comments

CAPTCHA image

Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.