Data Structure-Stack


Stack-Data Structure


Stack is LIFO(last in, first out) data structure. This will allow the stack data structure to add or remove its element only at the top.
The stack data structure is used commonly by compilers to manage memory for variables when a function is called. When a function is called the variables of the function will be pushed to the stack and these variables will be popped off the stack when the function returns to the caller. The most common operations of stack data structure is push (add item) and pop(remove item).

One way of creating a stack data structure is the modification of the linked list data structure by allowing the linked list element be added  or removed at the beginning. Therefore, we will modify the Insert and Delete methods of the double-linear linked list. The methods are changed from Insert to pus and from Delete to pop.

push method:

template <class Type>
void List<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 top of the list
else
{
ListElem<Type> *f;
f=pfirst;
pfirst=item;
pfirst->next=f;
f->prev=pfirst;
}
}

pop method:

template <class Type>
Type List<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;


}


}

To get the complete code of stack data structure, you can visit Stack data structure code



Comments

CAPTCHA image



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.