SlideShare a Scribd company logo
STACKS IN C++
INTRODUCTION TO STACK
DEFINITION:
 A stack is a data structure that provides temporary storage of data in such
a way that the element stored last will be retrieved first.
 This method is also called LIFO – Last In First Out.
EXAMPLE:
In real life we can think of stack as a stack of copies, stack of plates etc. The
first copy put in the stack is the last one to be removed. Similarly last copy to
put in the stack is the first one to be removed.
OPERATIONS ON STACK
 A stack is a linear data structure.
 It is controlled by two operations: push and pop.
 Both the operations take place from one end of the stack,
usually called top. Top points to the current top position of the
stack.
 Push operation adds an element to the top of the stack.
 Pop operation removes an element from the top of the stack.
 These two operations implements the LIFO method .
IMPLEMENTATION OF STACK
Stack can be implemented in two ways:
 As an Array
 As a Linked List
STACK AS AN ARRAY
Array implementation of stack uses
 an array to store data
 an integer type variable usually called the top, which
points to the top of the stack.
NOTE: The variable top contains the index number of
the top most filled element of the array.
30
20
10
2
4
3
2
1
0TOP
PUSH OPERATION
 Initially when the stack is empty, TOP can have any integer
value other than any valid index number of the array. Let TOP =
-1;
 The first element in the empty stack goes to the 0th position of
the array and the Top is initialized to value 0.
 After this every push operation increase the TOP by 1 and
inserts new data at that particular position.
 As arrays are fixed in length, elements can not be inserted
beyond the maximum size of the array. Pushing data beyond
the maximum size of the stack results in “data overflow”.
PUSH OPERATION EXPLAINED
NOTE: Pushing one more element into the stack will result in overflow.
POP OPERATION
The pop operation deletes the most recently entered item from
the stack.
Any attempt to delete an element from the empty stack results
in “data underflow” condition.
The variableTOP contains the index number of the current top
position of the stack.
Each time the pop operation is performed, theTOP variable is
decremented by 1.
POP OPERATION EXPLAINED
top = 2
PROGRAMTO ILLUSTRATE OPERATIONS ON
STACK AS AN INTEGER ARRAY
#include<iostream.h>
#include<process.h>
const int size=5
class stack
{ int arr[size];
int top; //top will point to the last item
//pushed onto the stack
public:
stack() { top=-1; } //constructor to create an
//empty stack, top=-1 indicate
//that no item is present in the array
void push(int item)
{ if(top==size-1)
cout<<”stack is full, given item cannot
be added”;
else
{ top++;
arr[top]=item;}
void pop()
{ if (top== -1)
cout<<”Stack is empty “;
else
{ cout<<arr[top];
top - -; }
}
void display()
{
for(int i=top;i>=0;i--)
cout<<arr[top];
}
void main()
{ stack s1;
int ch,data;
while(1)
{
cout<<”1.push”<<”n
2.pop”<<”n3.display”<<”n
4.exit”;
cout<<”Enter choice :”;
cin>>ch;
if (ch==1)
{ cout<<”enter item to
be pushed in the stack”;
cin>>data;
s1.push(data);
}
else if (ch == 2)
{ s1.pop(); }
else if (ch==3)
{ s1.display(); }
else
exit(-1);
} }
PROGRAMTO ILLUSTRATE OPERATIONS ON STACK
AS AN ARRAY OF OBJECTS
#include<iostream.h>
#include<process.h>
const int size=5
struct stu
{
int roll;
char name[20];
float total;
};
class stack
{ stu arr[size];
int top;
public:
stack() { top=-1; }
void push(int r, char
n[20],float tot)
{ if (top==size-1)
cout<<”overflow”;
else
{ top++;
arr[top].roll=r;
strcpy(arr[top].name,n);
arr[top].total=tot; }
void pop()
{ if (top== -1)
cout<<”Stack is empty “;
else
{ cout<<arr[top].roll<<
arr[top].name<<arr[top].tot;
top - -; }
void display()
{
for(int i=top;i>=0;i--)
cout<<arr[top].roll<<
arr[top].name<<arr[top].tot<<”n”;
}
void main()
{ stack s1;
int ch,data;
while(1)
{ cout<<”1.push”<<”n
2.pop”<<”n3.display”<<”n
4.exit”;
cout<<”Enter choice :”;
cin>>ch;
if (ch==1)
{ cin>>data;
s1.push(data); }
else if (ch == 2)
{ s1.pop(); }
else if (ch==3)
{ s1.display(); }
else
exit(-1); } }
APPLICATIONS OF STACK
A stack is an appropriate data structure on which information is stored and
then later retrieved in reverse order.The application of stack are as follows:
When a program executes, stack is used to store the return address at time
of function call. After the execution of the function is over, return address is
popped from stack and control is returned back to the calling function.
Converting an infix expression o postfix operation and to evaluate the
postfix expression.
Reversing an array, converting decimal number into binary number etc.
INFIX AND POSTFIX OPERATIONS
 The infix expression is a conventional algebraic expression, in
which the operator is in between the operands.
For example: a+b
 In the postfix expression the operator is placed after the
operands.
For example: ab+
NEED OF POSTFIX EXPRESSION
The postfix expressions are special because
 They do not use parenthesis
 The order of expression is uniquely reconstructed from the
expression itself.
These expressions are useful in computer applications.
CONVERTING INFIXTO POSTFIX EXPRESSION
CONVERT_I_P(I,P,STACK) Where I = infix expression, P = postfix expression, STACK = stack as an array
Step 1. Push ‘(‘ into STACK and add ‘)’ to the end of I.
Step 2. Scan expression I from left to right and repeat steps 3-6 for each element of I
until the stack is empty.
Step 3. If scanned element =‘(‘ , push it into the STACK.
Step 4. If scanned element = operand, add it to P.
Step 5. If scanned element = operator, then:
a) Repeatedly pop from STACK and add to P each operator from the top of
the stack until the operator at the top of the stack has lower precedence than
the operator extracted from I.
b) Add scanned operator to the top of the STACK.
Step 6. If scanned element = ‘)’ then:
a) Repeatedly pop from STACK and add to P each operator until the left
parenthesis is encountered.
b) Pop the left parenthesis but do not add to P.
CONVERTING INFIXTO POSTFIX EXPRESSION
Q Convert the following infix operation to
postfix operation.
((TRUE && FALSE) || ! (FALSE || TRUE))
Ans.The Postfix expression is:
TRUE FALSE && FALSETRUE || ! ||
EVALUATION OF POSTFIX EXPRESSION
Evaluate(P, result, STACK)
where P=Postfix expression, STACK =stack, result=to hold the result of evaluation
Step 1. Scan the postfix expression P from left to right and repeat the steps 2, 3
until the STACK is empty.
Step 2. If the scanned element = operand, push it into the STACK.
Step 3. If the scanned element = operator, then
a) Pop the two operands viz operand A and operand B from the STACK.
b) Evaluate ((operand B) operator (operand A))
c) Push the result of evaluation into the STACK.
Step 4. Set result=top most element of the STACK.
EVALUATING POSTFIX EXPRESSION
Q Evaluate the following Postfix expression:
TRUE FALSE || FALSE TRUE && ! ||
Ans. TRUE Step
No.
Symbol Scanned Operation Performed Stack Status
1 TRUE TRUE
2 FALSE TRUE FALSE
3 || TRUE || FALSE =TRUE TRUE
4 FALSE TRUE FALSE
5 TRUE TRUE FALSE TRUE
6 && FALSE &&TRUE = FALSE TRUE FALSE
7 ! ! FALSE =TRUE TRUE TRUE
8 || TRUE || TRUE TRUE
STACK AS A LINKED LIST
Linked list implementation of stack uses
 A linked list to store data
 A pointerTOP pointing to the top most position of the stack.
NOTE: Each node of a stack as a linked list has two parts : data part and link part and
is created with the help of self referential structure.
The data part stores the data and link part stores the address of the next node of the
linked list.
TOP
NODE
DATA LINK
PROGRAMTO ILLUSTRATE OPERATIONS ON STACK
AS A LINKED LIST
#include<iostream.h>
#include<conio.h>
struct node
{
int roll;
char name[20];
float total;
node *next;
};
class stack
{
node *top;
public :
stack()
{ top=NULL;}
void push();
void pop();
void display();
};
void stack::push()
{
node *temp;
temp=new node;
cout<<"Enter roll :";
cin>>temp->roll;
cout<<"Enter name :";
cin>>temp->name;
cout<<"Enter total :";
cin>>temp->total;
temp->next=top;
top=temp;
}
void stack::pop()
{
if(top!=NULL)
{
node *temp=top;
top=top->next;
cout<<temp->roll<<temp-
>name<<temp->total
<<"deleted";
delete temp;
}
else
cout<<"Stack empty";
}
void stack::display()
{
node *temp=top;
while(temp!=NULL)
{
cout<<temp->roll<<temp-
>name<<temp->total<<" ";
temp=temp->next;
} }
void main()
{ stack st;
char ch;
do
{ cout<<"stack
optionsnP push
nO Pop nD
Display nQ quit";
cin>>ch;
switch(ch)
{ case 'P':
st.push();break;
case 'O':
st.pop();break;
case 'D':
st.display();break;
}
}while(ch!='Q');
}
PROGRAMTO ILLUSTRATE OPERATIONS ON STACK
AS A LINKED LIST : Explanation
struct node
{
int roll;
char name[20];
float total;
node *next;
};
Self Referential Structure:These are special structures which
contains pointers to themselves.
Here, next is a pointer of type node itself.
Self Referential structures are needed to create Linked Lists.
class stack
{
node *top;
public :
stack()
{ top=NULL;}
void push();
void pop();
void display();
};
class stack: It contains pointerTOP which will point to the top
of the stack.
The constructor function initializesTOP to NULL.
PROGRAMTO ILLUSTRATE OPERATIONS ON STACK
AS A LINKED LIST : Explanation
void stack::push()
{
node *temp; // pointer of type node
temp=new node; // new operator will create a new
//node and address of new node
// is stored in temp
cout<<"Enter roll :";
cin>>temp->roll; These lines will input
cout<<"Enter name :"; values into roll , name
cin>>temp->name; and total of newly
cout<<"Enter total :"; created node.
cin>>temp->total;
temp->next=top; // address stored inTOP gets
//stored in next of newly
//created node.
top=temp; // Top will contain address of
// newly created node
}
void stack::pop()
{
if(top!=NULL) // if stack is not empty
{
node *temp=top; // temp is a pointer
//containing address of first node
top=top->next; // top will now contain address of
//second node
cout<<temp->roll<< //This line will display
temp->name<<temp->total // data stored in
<<"deleted"; // deleted node
delete temp; // delete operator will delete the node
// stored at temp
}
else
cout<<"Stack empty";}

More Related Content

What's hot

Queue data structure
Queue data structureQueue data structure
Queue data structure
anooppjoseph
 
Circular link list.ppt
Circular link list.pptCircular link list.ppt
Circular link list.ppt
Tirthika Bandi
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applications
somendra kumar
 
Array data structure
Array data structureArray data structure
Array data structure
maamir farooq
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
Sowmya Jyothi
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
shameen khan
 
stack & queue
stack & queuestack & queue
stack & queue
manju rani
 
Priority queue in DSA
Priority queue in DSAPriority queue in DSA
Priority queue in DSA
junnubabu
 
Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examplesgreatqadirgee4u
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
sagar yadav
 
Modular programming
Modular programmingModular programming
Arrays
ArraysArrays
Linked List
Linked ListLinked List
Linked List
Ashim Lamichhane
 
Linked List - Insertion & Deletion
Linked List - Insertion & DeletionLinked List - Insertion & Deletion
Linked List - Insertion & Deletion
Afaq Mansoor Khan
 
Stacks
StacksStacks
Stacks
sweta dargad
 
Linked list
Linked listLinked list
Linked list
Md. Afif Al Mamun
 
Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure
Janki Shah
 

What's hot (20)

Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Circular link list.ppt
Circular link list.pptCircular link list.ppt
Circular link list.ppt
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applications
 
Array data structure
Array data structureArray data structure
Array data structure
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
stack & queue
stack & queuestack & queue
stack & queue
 
Priority queue in DSA
Priority queue in DSAPriority queue in DSA
Priority queue in DSA
 
Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examples
 
Stack
StackStack
Stack
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Modular programming
Modular programmingModular programming
Modular programming
 
Arrays
ArraysArrays
Arrays
 
Linked List
Linked ListLinked List
Linked List
 
Heaps
HeapsHeaps
Heaps
 
single linked list
single linked listsingle linked list
single linked list
 
Linked List - Insertion & Deletion
Linked List - Insertion & DeletionLinked List - Insertion & Deletion
Linked List - Insertion & Deletion
 
Stacks
StacksStacks
Stacks
 
Linked list
Linked listLinked list
Linked list
 
Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure
 

Viewers also liked

Queues in C++
Queues in C++Queues in C++
Queues in C++
Vineeta Garg
 
3. Stack - Data Structures using C++ by Varsha Patil
3. Stack - Data Structures using C++ by Varsha Patil3. Stack - Data Structures using C++ by Varsha Patil
3. Stack - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
(2) cpp abstractions abstraction_and_encapsulation
(2) cpp abstractions abstraction_and_encapsulation(2) cpp abstractions abstraction_and_encapsulation
(2) cpp abstractions abstraction_and_encapsulation
Nico Ludwig
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
Michael Heron
 
Adaptive Query Optimization
Adaptive Query OptimizationAdaptive Query Optimization
Adaptive Query Optimization
Anju Garg
 
Vector class in C++
Vector class in C++Vector class in C++
Vector class in C++
Jawad Khan
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
Vineeta Garg
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
Vineeta Garg
 
Advanced data structures using c++ 3
Advanced data structures using c++ 3Advanced data structures using c++ 3
Advanced data structures using c++ 3Shaili Choudhary
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
Vineeta Garg
 
Structured query language constraints
Structured query language constraintsStructured query language constraints
Structured query language constraints
Vineeta Garg
 
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. PatilDiscrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
widespreadpromotion
 
Working with Cookies in NodeJS
Working with Cookies in NodeJSWorking with Cookies in NodeJS
Working with Cookies in NodeJS
Jay Dihenkar
 
Data types in c++
Data types in c++Data types in c++
Data types in c++
Venkata.Manish Reddy
 
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
widespreadpromotion
 

Viewers also liked (20)

Queues in C++
Queues in C++Queues in C++
Queues in C++
 
3. Stack - Data Structures using C++ by Varsha Patil
3. Stack - Data Structures using C++ by Varsha Patil3. Stack - Data Structures using C++ by Varsha Patil
3. Stack - Data Structures using C++ by Varsha Patil
 
(2) cpp abstractions abstraction_and_encapsulation
(2) cpp abstractions abstraction_and_encapsulation(2) cpp abstractions abstraction_and_encapsulation
(2) cpp abstractions abstraction_and_encapsulation
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
 
Lec3
Lec3Lec3
Lec3
 
Adaptive Query Optimization
Adaptive Query OptimizationAdaptive Query Optimization
Adaptive Query Optimization
 
Vector class in C++
Vector class in C++Vector class in C++
Vector class in C++
 
Qno 3 (a)
Qno 3 (a)Qno 3 (a)
Qno 3 (a)
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Advanced data structures using c++ 3
Advanced data structures using c++ 3Advanced data structures using c++ 3
Advanced data structures using c++ 3
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
 
Structured query language constraints
Structured query language constraintsStructured query language constraints
Structured query language constraints
 
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
 
Pp
PpPp
Pp
 
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. PatilDiscrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
 
Working with Cookies in NodeJS
Working with Cookies in NodeJSWorking with Cookies in NodeJS
Working with Cookies in NodeJS
 
Data types in c++
Data types in c++Data types in c++
Data types in c++
 
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
 
C++ data types
C++ data typesC++ data types
C++ data types
 

Similar to Stacks in c++

Stack data structure
Stack data structureStack data structure
Stack data structure
rogineojerio020496
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
nikshaikh786
 
Stack and its operations, Queue and its operations
Stack and its operations, Queue and its operationsStack and its operations, Queue and its operations
Stack and its operations, Queue and its operations
poongothai11
 
Data structure Stack
Data structure StackData structure Stack
Data structure Stack
Praveen Vishwakarma
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
Dabbal Singh Mahara
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
pinakspatel
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
KALPANAC20
 
04 stacks
04 stacks04 stacks
04 stacks
Rajan Gautam
 
Stack linked list
Stack linked listStack linked list
Stack linked listbhargav0077
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptx
haaamin01
 
DS UNIT1_STACKS.pptx
DS UNIT1_STACKS.pptxDS UNIT1_STACKS.pptx
DS UNIT1_STACKS.pptx
VeerannaKotagi1
 
stacks and queues
stacks and queuesstacks and queues
stacks and queues
DurgaDeviCbit
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacks
maamir farooq
 
CH4.pptx
CH4.pptxCH4.pptx
CH4.pptx
AliJama14
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
Apurbo Datta
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptx
line24arts
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queuestech4us
 
Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arora
kulachihansraj
 
Rana Junaid Rasheed
Rana Junaid RasheedRana Junaid Rasheed
Rana Junaid Rasheed
Rana junaid Rasheed
 
Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Getachew Ganfur
 

Similar to Stacks in c++ (20)

Stack data structure
Stack data structureStack data structure
Stack data structure
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Stack and its operations, Queue and its operations
Stack and its operations, Queue and its operationsStack and its operations, Queue and its operations
Stack and its operations, Queue and its operations
 
Data structure Stack
Data structure StackData structure Stack
Data structure Stack
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
 
04 stacks
04 stacks04 stacks
04 stacks
 
Stack linked list
Stack linked listStack linked list
Stack linked list
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptx
 
DS UNIT1_STACKS.pptx
DS UNIT1_STACKS.pptxDS UNIT1_STACKS.pptx
DS UNIT1_STACKS.pptx
 
stacks and queues
stacks and queuesstacks and queues
stacks and queues
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacks
 
CH4.pptx
CH4.pptxCH4.pptx
CH4.pptx
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptx
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queues
 
Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arora
 
Rana Junaid Rasheed
Rana Junaid RasheedRana Junaid Rasheed
Rana Junaid Rasheed
 
Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9
 

Recently uploaded

Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
goswamiyash170123
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
Krisztián Száraz
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
JEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questionsJEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questions
ShivajiThube2
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 

Recently uploaded (20)

Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
JEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questionsJEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questions
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 

Stacks in c++

  • 2. INTRODUCTION TO STACK DEFINITION:  A stack is a data structure that provides temporary storage of data in such a way that the element stored last will be retrieved first.  This method is also called LIFO – Last In First Out. EXAMPLE: In real life we can think of stack as a stack of copies, stack of plates etc. The first copy put in the stack is the last one to be removed. Similarly last copy to put in the stack is the first one to be removed.
  • 3. OPERATIONS ON STACK  A stack is a linear data structure.  It is controlled by two operations: push and pop.  Both the operations take place from one end of the stack, usually called top. Top points to the current top position of the stack.  Push operation adds an element to the top of the stack.  Pop operation removes an element from the top of the stack.  These two operations implements the LIFO method .
  • 4. IMPLEMENTATION OF STACK Stack can be implemented in two ways:  As an Array  As a Linked List
  • 5. STACK AS AN ARRAY Array implementation of stack uses  an array to store data  an integer type variable usually called the top, which points to the top of the stack. NOTE: The variable top contains the index number of the top most filled element of the array. 30 20 10 2 4 3 2 1 0TOP
  • 6. PUSH OPERATION  Initially when the stack is empty, TOP can have any integer value other than any valid index number of the array. Let TOP = -1;  The first element in the empty stack goes to the 0th position of the array and the Top is initialized to value 0.  After this every push operation increase the TOP by 1 and inserts new data at that particular position.  As arrays are fixed in length, elements can not be inserted beyond the maximum size of the array. Pushing data beyond the maximum size of the stack results in “data overflow”.
  • 7. PUSH OPERATION EXPLAINED NOTE: Pushing one more element into the stack will result in overflow.
  • 8. POP OPERATION The pop operation deletes the most recently entered item from the stack. Any attempt to delete an element from the empty stack results in “data underflow” condition. The variableTOP contains the index number of the current top position of the stack. Each time the pop operation is performed, theTOP variable is decremented by 1.
  • 10. PROGRAMTO ILLUSTRATE OPERATIONS ON STACK AS AN INTEGER ARRAY #include<iostream.h> #include<process.h> const int size=5 class stack { int arr[size]; int top; //top will point to the last item //pushed onto the stack public: stack() { top=-1; } //constructor to create an //empty stack, top=-1 indicate //that no item is present in the array void push(int item) { if(top==size-1) cout<<”stack is full, given item cannot be added”; else { top++; arr[top]=item;} void pop() { if (top== -1) cout<<”Stack is empty “; else { cout<<arr[top]; top - -; } } void display() { for(int i=top;i>=0;i--) cout<<arr[top]; } void main() { stack s1; int ch,data; while(1) { cout<<”1.push”<<”n 2.pop”<<”n3.display”<<”n 4.exit”; cout<<”Enter choice :”; cin>>ch; if (ch==1) { cout<<”enter item to be pushed in the stack”; cin>>data; s1.push(data); } else if (ch == 2) { s1.pop(); } else if (ch==3) { s1.display(); } else exit(-1); } }
  • 11. PROGRAMTO ILLUSTRATE OPERATIONS ON STACK AS AN ARRAY OF OBJECTS #include<iostream.h> #include<process.h> const int size=5 struct stu { int roll; char name[20]; float total; }; class stack { stu arr[size]; int top; public: stack() { top=-1; } void push(int r, char n[20],float tot) { if (top==size-1) cout<<”overflow”; else { top++; arr[top].roll=r; strcpy(arr[top].name,n); arr[top].total=tot; } void pop() { if (top== -1) cout<<”Stack is empty “; else { cout<<arr[top].roll<< arr[top].name<<arr[top].tot; top - -; } void display() { for(int i=top;i>=0;i--) cout<<arr[top].roll<< arr[top].name<<arr[top].tot<<”n”; } void main() { stack s1; int ch,data; while(1) { cout<<”1.push”<<”n 2.pop”<<”n3.display”<<”n 4.exit”; cout<<”Enter choice :”; cin>>ch; if (ch==1) { cin>>data; s1.push(data); } else if (ch == 2) { s1.pop(); } else if (ch==3) { s1.display(); } else exit(-1); } }
  • 12. APPLICATIONS OF STACK A stack is an appropriate data structure on which information is stored and then later retrieved in reverse order.The application of stack are as follows: When a program executes, stack is used to store the return address at time of function call. After the execution of the function is over, return address is popped from stack and control is returned back to the calling function. Converting an infix expression o postfix operation and to evaluate the postfix expression. Reversing an array, converting decimal number into binary number etc.
  • 13. INFIX AND POSTFIX OPERATIONS  The infix expression is a conventional algebraic expression, in which the operator is in between the operands. For example: a+b  In the postfix expression the operator is placed after the operands. For example: ab+
  • 14. NEED OF POSTFIX EXPRESSION The postfix expressions are special because  They do not use parenthesis  The order of expression is uniquely reconstructed from the expression itself. These expressions are useful in computer applications.
  • 15. CONVERTING INFIXTO POSTFIX EXPRESSION CONVERT_I_P(I,P,STACK) Where I = infix expression, P = postfix expression, STACK = stack as an array Step 1. Push ‘(‘ into STACK and add ‘)’ to the end of I. Step 2. Scan expression I from left to right and repeat steps 3-6 for each element of I until the stack is empty. Step 3. If scanned element =‘(‘ , push it into the STACK. Step 4. If scanned element = operand, add it to P. Step 5. If scanned element = operator, then: a) Repeatedly pop from STACK and add to P each operator from the top of the stack until the operator at the top of the stack has lower precedence than the operator extracted from I. b) Add scanned operator to the top of the STACK. Step 6. If scanned element = ‘)’ then: a) Repeatedly pop from STACK and add to P each operator until the left parenthesis is encountered. b) Pop the left parenthesis but do not add to P.
  • 16. CONVERTING INFIXTO POSTFIX EXPRESSION Q Convert the following infix operation to postfix operation. ((TRUE && FALSE) || ! (FALSE || TRUE)) Ans.The Postfix expression is: TRUE FALSE && FALSETRUE || ! ||
  • 17. EVALUATION OF POSTFIX EXPRESSION Evaluate(P, result, STACK) where P=Postfix expression, STACK =stack, result=to hold the result of evaluation Step 1. Scan the postfix expression P from left to right and repeat the steps 2, 3 until the STACK is empty. Step 2. If the scanned element = operand, push it into the STACK. Step 3. If the scanned element = operator, then a) Pop the two operands viz operand A and operand B from the STACK. b) Evaluate ((operand B) operator (operand A)) c) Push the result of evaluation into the STACK. Step 4. Set result=top most element of the STACK.
  • 18. EVALUATING POSTFIX EXPRESSION Q Evaluate the following Postfix expression: TRUE FALSE || FALSE TRUE && ! || Ans. TRUE Step No. Symbol Scanned Operation Performed Stack Status 1 TRUE TRUE 2 FALSE TRUE FALSE 3 || TRUE || FALSE =TRUE TRUE 4 FALSE TRUE FALSE 5 TRUE TRUE FALSE TRUE 6 && FALSE &&TRUE = FALSE TRUE FALSE 7 ! ! FALSE =TRUE TRUE TRUE 8 || TRUE || TRUE TRUE
  • 19. STACK AS A LINKED LIST Linked list implementation of stack uses  A linked list to store data  A pointerTOP pointing to the top most position of the stack. NOTE: Each node of a stack as a linked list has two parts : data part and link part and is created with the help of self referential structure. The data part stores the data and link part stores the address of the next node of the linked list. TOP NODE DATA LINK
  • 20. PROGRAMTO ILLUSTRATE OPERATIONS ON STACK AS A LINKED LIST #include<iostream.h> #include<conio.h> struct node { int roll; char name[20]; float total; node *next; }; class stack { node *top; public : stack() { top=NULL;} void push(); void pop(); void display(); }; void stack::push() { node *temp; temp=new node; cout<<"Enter roll :"; cin>>temp->roll; cout<<"Enter name :"; cin>>temp->name; cout<<"Enter total :"; cin>>temp->total; temp->next=top; top=temp; } void stack::pop() { if(top!=NULL) { node *temp=top; top=top->next; cout<<temp->roll<<temp- >name<<temp->total <<"deleted"; delete temp; } else cout<<"Stack empty"; } void stack::display() { node *temp=top; while(temp!=NULL) { cout<<temp->roll<<temp- >name<<temp->total<<" "; temp=temp->next; } } void main() { stack st; char ch; do { cout<<"stack optionsnP push nO Pop nD Display nQ quit"; cin>>ch; switch(ch) { case 'P': st.push();break; case 'O': st.pop();break; case 'D': st.display();break; } }while(ch!='Q'); }
  • 21. PROGRAMTO ILLUSTRATE OPERATIONS ON STACK AS A LINKED LIST : Explanation struct node { int roll; char name[20]; float total; node *next; }; Self Referential Structure:These are special structures which contains pointers to themselves. Here, next is a pointer of type node itself. Self Referential structures are needed to create Linked Lists. class stack { node *top; public : stack() { top=NULL;} void push(); void pop(); void display(); }; class stack: It contains pointerTOP which will point to the top of the stack. The constructor function initializesTOP to NULL.
  • 22. PROGRAMTO ILLUSTRATE OPERATIONS ON STACK AS A LINKED LIST : Explanation void stack::push() { node *temp; // pointer of type node temp=new node; // new operator will create a new //node and address of new node // is stored in temp cout<<"Enter roll :"; cin>>temp->roll; These lines will input cout<<"Enter name :"; values into roll , name cin>>temp->name; and total of newly cout<<"Enter total :"; created node. cin>>temp->total; temp->next=top; // address stored inTOP gets //stored in next of newly //created node. top=temp; // Top will contain address of // newly created node } void stack::pop() { if(top!=NULL) // if stack is not empty { node *temp=top; // temp is a pointer //containing address of first node top=top->next; // top will now contain address of //second node cout<<temp->roll<< //This line will display temp->name<<temp->total // data stored in <<"deleted"; // deleted node delete temp; // delete operator will delete the node // stored at temp } else cout<<"Stack empty";}