Pages

Tuesday, December 16, 2014

How to use Stack in C/C++ programs


This is an example program showing the syntax for stack declaration and manipulation on that stack using push and pop operations defined in the <stack> library. Other auxiliary functions of stack library like size() and top() are also used in the program. 

  • Push operation is used to insert an element in a stack
  • Pop operation is used to remove an element from a stack 

Property of Stack:

The element pushed in to the stack will always reside at the top of the stack.

The element popped up from stack will always be the top element from the stack.

Depiction of Stack push and pop Functions.









Try to run the below code in your C compiler and understand the  syntax and usage of the Stack Library 


#include<iostream>
#include<stack>

using namespace std;

int main()

{

stack <string> cards;    
\\ Declaration of Stack which 
\\can contain elements of "String" Type and
\\name of the stack assigned is "cards"

cards.push("kings of hearts");  \\ push an element
cards.push("kings of club");
cards.push("kings of spade");
cards.push("kings of diamond");

\\ size() function gives the
 \\ number of elements in the stack  
cout<<"there are"<<cards.size()<<"cards in the deck";

cards.push("ace of Spade");
cards.push("ace of hearts");

\\ top() function of stack library returns 
 \\ the element residing at the top position of the stack

string topcard=cards.top();  


cout<<"\ntop card is\t"<<topcard;

\\pop() function of stack library will 
\\simply delete the top element from the top
\\and the next element below it will be updated
\\ as new top of the stack

cards.pop();  

cout<<"\ntop card is\t"<<cards.top();
}

No comments:

Post a Comment