SlideShare a Scribd company logo
1 of 30
1
Stacks
2
Stacks
“A Stack is a special kind of list in which all
insertions and deletions take place at one
end, called the Top”
Other Names
 Pushdown List
 Last In First Out (LIFO)
3
Stacks
Examples:
 Books on a floor
 Dishes on a shelf
4
Common Operations on Stacks
1. MAKENULL(S): Make Stack S be an empty
stack.
2. TOP(S): Return the element at the top of stack
S.
3. POP(S): Remove the top element of the stack.
4. PUSH(S): Insert the element x at the top of the
stack.
5. EMPTY(S): Return true if S is an empty stack;
return false otherwise.
5
Static and Dynamic Stacks
There are two kinds of stack data
structure -
a) static, i.e. they have a fixed size, and are
implemented as arrays.
b) dynamic, i.e. they grow in size as needed,
and implemented as linked lists
6
Push and Pop operations of Stack
7
An Array Implementation of Stacks
First Implementation
 Elements are stored in contiguous cells of an array.
 New elements can be inserted to the top of the list.
Last Element
Second Element
First Element
List
Empty
maxlength
top
8
An Array Implementation of Stacks
Problem with this implementation
 Every PUSH and POP requires moving the entire
array up and down.
1
1
2
1
2
3
1
2
9
Since, in a stack the insertion and deletion
take place only at the top, so…
A better Implementation:
 Anchor the bottom of the stack at the
bottom of the array
 Let the stack grow towards the top of the
array
 Top indicates the current position of the
first stack element.
An Array Implementation of Stacks
10
A better Implementation:
First Element
Last Element
maxlength
top
Second Element
1
2
.
.
An Array Implementation of Stacks
11
A Stack Class
#ifndef INTSTACK_H
#define INTSTACK_H
class IntStack
{
private:
int *stackArray;
int stackSize;
int top;
public:
IntStack(int);
void push(int);
void pop(int &);
bool isFull(void);
bool isEmpty(void);
};
#endif
12
Implementation
//*******************
// Constructor *
//*******************
IntStack::IntStack(int size)
{
stackArray = new int[size];
stackSize = size;
top = -1;
}
13
Push
// Member function push pushes the argument
onto *
// the stack. *
void IntStack::push(int num)
{
if (isFull())
cout << "The stack is full.n";
else
{
top++;
stackArray[top] = num;
}
}
14
// Member function pop pops the value at the top
// of the stack off, and copies it into the variable
// passed as an argument.
void IntStack::pop(int &num)
{
if (isEmpty())
cout << "The stack is empty.n";
else
{
num = stackArray[top];
top--;
}
}
15
//***************************************************
// Member function isFull returns true if the stack *
// is full, or false otherwise. *
//***************************************************
bool IntStack::isFull(void)
{
bool status;
if (top == stackSize - 1)
status = true;
else
status = false;
return status;
}
16
//**********************************************
// Member funciton isEmpty returns true if the
//stack *
// is empty, or false otherwise.*
//***********************************************
bool IntStack::isEmpty(void)
{
bool status;
if (top == -1)
status = true;
else
status = false;
return status;
}
17
// This program demonstrates the IntStack class.
#include <iostream.h>
#include "intstack.h“
void main(void)
{
IntStack stack(5);
int catchVar;
cout << "Pushing 5n";
stack.push(5);
cout << "Pushing 10n";
stack.push(10);
cout << "Pushing 15n";
stack.push(15);
cout << "Pushing 20n";
stack.push(20);
cout << "Pushing 25n";
stack.push(25);
18
cout << "Popping...n";
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
}
19
Program Output
Pushing 5
Pushing 10
Pushing 15
Pushing 20
Pushing 25
Popping...
25
20
15
10
5
20
About Program 1
• In the program, the constructor is called
with the argument 5. This sets up the
member variables as shown in Figure 1.
Since top is set to –1, the stack is empty
21
• Figure 3 shows the state of the member
variables after all five calls to the push
function. Now the top of the stack is at
element 4, and the stack is full.
22
Notice that the pop function uses a reference
parameter, num.
The value that is popped off the stack is copied into
num so it can be used later in the program.
Figure 4 (on the next slide) depicts the state of
the class members, and the num parameter, just
after the first value is popped off the stack.
23
Implementing other Stack Operations
More complex operations can be built on the basic stack class we
have just described, e.g. a class called MathStack.
MathStack has 2 member functions :- add( ) sub( )
24
Stack Templates
The stack class so far work with integers
only. A stack template can be used to
work with any data type.
25
A Linked-List Implementation of Stacks
Stack can expand or shrink with each
PUSH or POP operation.
PUSH and POP operate only on the
header cell and the first cell on the list.
x y .z
Top
26
Linked List Implementation of Stack
class Stack
{
struct node
{
int data;
node *next;
}*top;
public:
void Push(int newelement);
int Pop(void);
bool IsEmpty();
};
27
void Stack::Push(int newelement)
{
node *newptr;
newptr=new node;
newptr->data=newelement;
newptr->next=top;
top=newptr;
}
int Stack:Pop(void)
{
if (IsEmpty()) { cout<<“underflow error”; return;}
tempptr=top;
int returnvalue=top->data;
top=top->next;
delete tempptr;
return returnvalue;
}
28
void Stack::IsEmpty()
{
if (top==NULL) return true;
else return false;
}
29
Program 3
// This program demonstrates the dynamic stack
// class DynIntClass.
#include <iostream.h>
#include "dynintstack.h“
void main(void)
{
DynIntStack stack;
int catchVar;
cout << "Pushing 5n";
stack.push(5);
cout << "Pushing 10n";
stack.push(10);
cout << "Pushing 15n";
stack.push(15);
30
cout << "Popping...n";
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
cout << "nAttempting to pop again... ";
stack.pop(catchVar);
}
Program Output
Pushing 5
Pushing 10
Pushing 15
Popping...
15
10
5
Attempting to pop again... The stack is empty.

More Related Content

What's hot (20)

Stack data structure
Stack data structureStack data structure
Stack data structure
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Stack
StackStack
Stack
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Stack
StackStack
Stack
 
Stack
StackStack
Stack
 
10 Linked Lists Sacks and Queues
10 Linked Lists Sacks and Queues10 Linked Lists Sacks and Queues
10 Linked Lists Sacks and Queues
 
5 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart25 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart2
 
Data structure Stack
Data structure StackData structure Stack
Data structure Stack
 
Stack of Data structure
Stack of Data structureStack of Data structure
Stack of Data structure
 
Stack linked list
Stack linked listStack linked list
Stack linked list
 
Stacks, Queues, Deques
Stacks, Queues, DequesStacks, Queues, Deques
Stacks, Queues, Deques
 
Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arora
 
Stack & Queue using Linked List in Data Structure
Stack & Queue using Linked List in Data StructureStack & Queue using Linked List in Data Structure
Stack & Queue using Linked List in Data Structure
 
Csa stack
Csa stackCsa stack
Csa stack
 
Project of data structure
Project of data structureProject of data structure
Project of data structure
 
Migration
MigrationMigration
Migration
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 Data Structures - Lecture 9 [Stack & Queue using Linked List] Data Structures - Lecture 9 [Stack & Queue using Linked List]
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 
Stack & heap
Stack & heap Stack & heap
Stack & heap
 
stack presentation
stack presentationstack presentation
stack presentation
 

Viewers also liked (7)

Analysis of Algorithum
Analysis of AlgorithumAnalysis of Algorithum
Analysis of Algorithum
 
Sorting algos > Data Structures & Algorithums
Sorting algos  > Data Structures & AlgorithumsSorting algos  > Data Structures & Algorithums
Sorting algos > Data Structures & Algorithums
 
Algo>Queues
Algo>QueuesAlgo>Queues
Algo>Queues
 
Algo>ADT list & linked list
Algo>ADT list & linked listAlgo>ADT list & linked list
Algo>ADT list & linked list
 
RDBMS
RDBMSRDBMS
RDBMS
 
Algo>Arrays
Algo>ArraysAlgo>Arrays
Algo>Arrays
 
Application of Stacks
Application of StacksApplication of Stacks
Application of Stacks
 

Similar to Algo>Stacks

Presentation topic is stick data structure
Presentation topic is stick data structurePresentation topic is stick data structure
Presentation topic is stick data structureAizazAli21
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptxline24arts
 
Given the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxGiven the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxshericehewat
 
Stack and its applications
Stack and its applicationsStack and its applications
Stack and its applicationsAhsan Mansiv
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manualnikshaikh786
 
Introduction to stack
Introduction to stackIntroduction to stack
Introduction to stackvaibhav2910
 
Data Structure.pptx
Data Structure.pptxData Structure.pptx
Data Structure.pptxSajalFayyaz
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queuePulkitmodi1998
 

Similar to Algo>Stacks (20)

Presentation topic is stick data structure
Presentation topic is stick data structurePresentation topic is stick data structure
Presentation topic is stick data structure
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptx
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Given the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxGiven the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docx
 
Stack and its applications
Stack and its applicationsStack and its applications
Stack and its applications
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
MO 2020 DS Stacks 1 AB.ppt
MO 2020 DS Stacks 1 AB.pptMO 2020 DS Stacks 1 AB.ppt
MO 2020 DS Stacks 1 AB.ppt
 
STACK1.pptx
STACK1.pptxSTACK1.pptx
STACK1.pptx
 
104332 sri vidhya eng notes
104332 sri vidhya eng notes104332 sri vidhya eng notes
104332 sri vidhya eng notes
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
Stack
StackStack
Stack
 
Stack in C.pptx
Stack in C.pptxStack in C.pptx
Stack in C.pptx
 
Introduction to stack
Introduction to stackIntroduction to stack
Introduction to stack
 
Data Structure.pptx
Data Structure.pptxData Structure.pptx
Data Structure.pptx
 
Stack.pptx
Stack.pptxStack.pptx
Stack.pptx
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 

More from Ain-ul-Moiz Khawaja

More from Ain-ul-Moiz Khawaja (11)

Algo>Abstract data type
Algo>Abstract data typeAlgo>Abstract data type
Algo>Abstract data type
 
Algorithum Analysis
Algorithum AnalysisAlgorithum Analysis
Algorithum Analysis
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & Algorithums
 
Huffman > Data Structures & Algorithums
Huffman > Data Structures & AlgorithumsHuffman > Data Structures & Algorithums
Huffman > Data Structures & Algorithums
 
Graphs > Discrete structures , Data Structures & Algorithums
Graphs > Discrete structures , Data Structures & AlgorithumsGraphs > Discrete structures , Data Structures & Algorithums
Graphs > Discrete structures , Data Structures & Algorithums
 
Data Structures & Algorithms
Data Structures & AlgorithmsData Structures & Algorithms
Data Structures & Algorithms
 
Turn over
Turn overTurn over
Turn over
 
Attribution Theories
Attribution TheoriesAttribution Theories
Attribution Theories
 
Attribution Theory
Attribution TheoryAttribution Theory
Attribution Theory
 
Absenteeism
AbsenteeismAbsenteeism
Absenteeism
 
HRM Employee Turnover
HRM Employee TurnoverHRM Employee Turnover
HRM Employee Turnover
 

Recently uploaded

Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
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
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
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
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
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
 
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
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
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
 

Recently uploaded (20)

Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
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
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
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...
 
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...
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
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 ...
 

Algo>Stacks

  • 2. 2 Stacks “A Stack is a special kind of list in which all insertions and deletions take place at one end, called the Top” Other Names  Pushdown List  Last In First Out (LIFO)
  • 3. 3 Stacks Examples:  Books on a floor  Dishes on a shelf
  • 4. 4 Common Operations on Stacks 1. MAKENULL(S): Make Stack S be an empty stack. 2. TOP(S): Return the element at the top of stack S. 3. POP(S): Remove the top element of the stack. 4. PUSH(S): Insert the element x at the top of the stack. 5. EMPTY(S): Return true if S is an empty stack; return false otherwise.
  • 5. 5 Static and Dynamic Stacks There are two kinds of stack data structure - a) static, i.e. they have a fixed size, and are implemented as arrays. b) dynamic, i.e. they grow in size as needed, and implemented as linked lists
  • 6. 6 Push and Pop operations of Stack
  • 7. 7 An Array Implementation of Stacks First Implementation  Elements are stored in contiguous cells of an array.  New elements can be inserted to the top of the list. Last Element Second Element First Element List Empty maxlength top
  • 8. 8 An Array Implementation of Stacks Problem with this implementation  Every PUSH and POP requires moving the entire array up and down. 1 1 2 1 2 3 1 2
  • 9. 9 Since, in a stack the insertion and deletion take place only at the top, so… A better Implementation:  Anchor the bottom of the stack at the bottom of the array  Let the stack grow towards the top of the array  Top indicates the current position of the first stack element. An Array Implementation of Stacks
  • 10. 10 A better Implementation: First Element Last Element maxlength top Second Element 1 2 . . An Array Implementation of Stacks
  • 11. 11 A Stack Class #ifndef INTSTACK_H #define INTSTACK_H class IntStack { private: int *stackArray; int stackSize; int top; public: IntStack(int); void push(int); void pop(int &); bool isFull(void); bool isEmpty(void); }; #endif
  • 12. 12 Implementation //******************* // Constructor * //******************* IntStack::IntStack(int size) { stackArray = new int[size]; stackSize = size; top = -1; }
  • 13. 13 Push // Member function push pushes the argument onto * // the stack. * void IntStack::push(int num) { if (isFull()) cout << "The stack is full.n"; else { top++; stackArray[top] = num; } }
  • 14. 14 // Member function pop pops the value at the top // of the stack off, and copies it into the variable // passed as an argument. void IntStack::pop(int &num) { if (isEmpty()) cout << "The stack is empty.n"; else { num = stackArray[top]; top--; } }
  • 15. 15 //*************************************************** // Member function isFull returns true if the stack * // is full, or false otherwise. * //*************************************************** bool IntStack::isFull(void) { bool status; if (top == stackSize - 1) status = true; else status = false; return status; }
  • 16. 16 //********************************************** // Member funciton isEmpty returns true if the //stack * // is empty, or false otherwise.* //*********************************************** bool IntStack::isEmpty(void) { bool status; if (top == -1) status = true; else status = false; return status; }
  • 17. 17 // This program demonstrates the IntStack class. #include <iostream.h> #include "intstack.h“ void main(void) { IntStack stack(5); int catchVar; cout << "Pushing 5n"; stack.push(5); cout << "Pushing 10n"; stack.push(10); cout << "Pushing 15n"; stack.push(15); cout << "Pushing 20n"; stack.push(20); cout << "Pushing 25n"; stack.push(25);
  • 18. 18 cout << "Popping...n"; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; }
  • 19. 19 Program Output Pushing 5 Pushing 10 Pushing 15 Pushing 20 Pushing 25 Popping... 25 20 15 10 5
  • 20. 20 About Program 1 • In the program, the constructor is called with the argument 5. This sets up the member variables as shown in Figure 1. Since top is set to –1, the stack is empty
  • 21. 21 • Figure 3 shows the state of the member variables after all five calls to the push function. Now the top of the stack is at element 4, and the stack is full.
  • 22. 22 Notice that the pop function uses a reference parameter, num. The value that is popped off the stack is copied into num so it can be used later in the program. Figure 4 (on the next slide) depicts the state of the class members, and the num parameter, just after the first value is popped off the stack.
  • 23. 23 Implementing other Stack Operations More complex operations can be built on the basic stack class we have just described, e.g. a class called MathStack. MathStack has 2 member functions :- add( ) sub( )
  • 24. 24 Stack Templates The stack class so far work with integers only. A stack template can be used to work with any data type.
  • 25. 25 A Linked-List Implementation of Stacks Stack can expand or shrink with each PUSH or POP operation. PUSH and POP operate only on the header cell and the first cell on the list. x y .z Top
  • 26. 26 Linked List Implementation of Stack class Stack { struct node { int data; node *next; }*top; public: void Push(int newelement); int Pop(void); bool IsEmpty(); };
  • 27. 27 void Stack::Push(int newelement) { node *newptr; newptr=new node; newptr->data=newelement; newptr->next=top; top=newptr; } int Stack:Pop(void) { if (IsEmpty()) { cout<<“underflow error”; return;} tempptr=top; int returnvalue=top->data; top=top->next; delete tempptr; return returnvalue; }
  • 28. 28 void Stack::IsEmpty() { if (top==NULL) return true; else return false; }
  • 29. 29 Program 3 // This program demonstrates the dynamic stack // class DynIntClass. #include <iostream.h> #include "dynintstack.h“ void main(void) { DynIntStack stack; int catchVar; cout << "Pushing 5n"; stack.push(5); cout << "Pushing 10n"; stack.push(10); cout << "Pushing 15n"; stack.push(15);
  • 30. 30 cout << "Popping...n"; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; cout << "nAttempting to pop again... "; stack.pop(catchVar); } Program Output Pushing 5 Pushing 10 Pushing 15 Popping... 15 10 5 Attempting to pop again... The stack is empty.

Editor's Notes

  1. But NO constraints on HOW the problem is solved