SlideShare uma empresa Scribd logo
1 de 22
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";}

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Arrays
ArraysArrays
Arrays
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Stack a Data Structure
Stack a Data StructureStack a Data Structure
Stack a Data Structure
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure ppt
 
Data structures using c
Data structures using cData structures using c
Data structures using c
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURE
 
Bubble sort
Bubble sortBubble sort
Bubble sort
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
Presentation on queue
Presentation on queuePresentation on queue
Presentation on queue
 
Introduction to Array ppt
Introduction to Array pptIntroduction to Array ppt
Introduction to Array ppt
 
Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive
 
stack presentation
stack presentationstack presentation
stack presentation
 
Circular link list.ppt
Circular link list.pptCircular link list.ppt
Circular link list.ppt
 
Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADT
 
Stacks
StacksStacks
Stacks
 
Structure in C
Structure in CStructure in C
Structure in C
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Terminology of tree
Terminology of treeTerminology of tree
Terminology of tree
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 

Destaque

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 Patilwidespreadpromotion
 
(2) cpp abstractions abstraction_and_encapsulation
(2) cpp abstractions abstraction_and_encapsulation(2) cpp abstractions abstraction_and_encapsulation
(2) cpp abstractions abstraction_and_encapsulationNico Ludwig
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - AbstractionMichael Heron
 
Adaptive Query Optimization
Adaptive Query OptimizationAdaptive Query Optimization
Adaptive Query OptimizationAnju 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 objects1Vineeta Garg
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsVineeta 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 functionsVineeta Garg
 
Structured query language constraints
Structured query language constraintsStructured query language constraints
Structured query language constraintsVineeta 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 Patilwidespreadpromotion
 
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. Patilwidespreadpromotion
 
Working with Cookies in NodeJS
Working with Cookies in NodeJSWorking with Cookies in NodeJS
Working with Cookies in NodeJSJay Dihenkar
 
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 Patilwidespreadpromotion
 

Destaque (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
 

Semelhante a Stacks in c++

Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manualnikshaikh786
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-listpinakspatel
 
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.pptxKALPANAC20
 
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) .pptxhaaamin01
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacksmaamir farooq
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESSowmya Jyothi
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptxline24arts
 
Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arorakulachihansraj
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queuestech4us
 
Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Getachew Ganfur
 
Unit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxUnit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxYogesh Pawar
 

Semelhante a 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
 
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
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptx
 
Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arora
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queues
 
Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9
 
Rana Junaid Rasheed
Rana Junaid RasheedRana Junaid Rasheed
Rana Junaid Rasheed
 
Unit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxUnit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptx
 

Último

9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 

Último (20)

9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 

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";}