SlideShare a Scribd company logo
Stacks
CS 302 – Data Structures
Sections 5.1, 5.2, 6.1, 6.5
Warning
• Although data structure concepts between
this and last semesters will be the same,
there might be implementation differences.
• Your answers in questions in quizzes and
exams should be based on this semester’s
(CS302) implementations!
Definitions
• ImageType.h
• ImageType.cpp
• Driver.cpp
class specification
class implementation
application
(client code)
Question
• In object oriented programming, class
implementation details are hidden from
applications that use the class.
• Why?
What is a stack?
• It is an ordered group of homogeneous items.
• Items are added to and removed from the top of the stack
LIFO property: Last In, First Out
• The last item added would be the first to be removed
TOP OF THE STACK TOP OF THE STACK
Stack Implementations
Array-based
Linked-list-based
Array-based Stacks
template<class ItemType>
class StackType {
public:
StackType(int);
void MakeEmpty();
bool IsEmpty() const;
bool IsFull() const;
void Push(ItemType);
void Pop(ItemType&);
private:
int top, maxStack;
ItemType *items;
};
dynamically allocated array
Array-based Stacks (cont’d)
template<class ItemType>
StackType<ItemType>::StackType(int size)
{
top = -1;
maxStack = size;
items = new ItemType[max];
}
template<class ItemType>
StackType<ItemType>::~StackType()
{
delete [ ] items;
}
O(1)
O(1)
Array-based Stacks (cont’d)
template<class ItemType>
void StackType<ItemType>::MakeEmpty()
{
top = -1;
} O(1)
Array-based Stacks (cont.)
template<class ItemType>
bool StackType<ItemType>::IsEmpty() const
{
return (top == -1);
}
template<class ItemType>
bool StackType<ItemType>::IsFull() const
{
return (top == maxStack-1);
}
O(1)
O(1)
Push (ItemType newItem)
• Function: Adds newItem to the top of
the stack.
• Preconditions: Stack has been
initialized and is not full.
• Postconditions: newItem is at the top
of the stack.
Stack overflow
• The condition resulting from trying to push
an element onto a full stack.
if(!stack.IsFull())
stack.Push(item);
Array-based Stacks (cont.)
template<class ItemType>
void StackType<ItemType>::Push(ItemType newItem)
{
top++;
items[top] = newItem;
} O(1)
Pop (ItemType& item)
• Function: Removes topItem from stack and
returns it in item.
• Preconditions: Stack has been initialized
and is not empty.
• Postconditions: Top element has been
removed from stack and item is a copy of
the removed element.
Stack underflow
• The condition resulting from trying to pop
an empty stack.
if(!stack.IsEmpty())
stack.Pop(item);
Array-based Stacks (cont.)
template<class ItemType>
void StackType<ItemType>::Pop(ItemType& item)
{
item = items[top];
top--;
}
O(1)
Templates
• Templates allow the compiler to generate multiple
versions of a class type by allowing parameterized
types.
• Compiler generates distinct class types and gives
its own internal name to each of the types.
Compiling Templates
• Cannot anymore compile StackType.cpp separately
from the application of the class (e.g., driver.cpp)
• Compiler needs to know the data type of the stack
to instantiate the class!
• Where can the compiler find this information?
Compiling Templates (cont’d)
// Client code
StackType<int> myStack;
StackType<float> yourStack;
StackType<StrType> anotherStack;
myStack.Push(35);
yourStack.Push(584.39);
Compiling Templates (cont’d)
• Must compile StackType.cpp and client code (e.g.,
driver.cpp) together!
(1) Use “include” directive to include StackType.cpp
StackType.cpp at the end
of StackType.h
StackType.h
(2) “include” StackType.h
StackType.h in client’s code
(3) Compile client code
Linked-list-based Stacks
template<class ItemType>
struct NodeType<ItemType> {
ItemType info;
NodeType<ItemType>* next;
};
Linked-list-based Stacks (cont’d)
template<class ItemType>
struct NodeType<ItemType>;
template<class ItemType>
class StackType {
public:
StackType();
~StackType();
void MakeEmpty();
bool IsEmpty() const;
bool IsFull() const;
void Push(ItemType);
void Pop(ItemType&);
private:
NodeType<ItemType>* topPtr;
};
Linked-list-based Stacks (cont’d)
template<class ItemType>
StackType<ItemType>::StackType()
StackType()
{
topPtr = NULL;
}
template<class ItemType>
void StackType<ItemType>::MakeEmpty()
MakeEmpty()
{
NodeType<ItemType>* tempPtr;
while(topPtr != NULL) {
tempPtr = topPtr;
topPtr = topPtr->next;
delete tempPtr;
}
}
O(N)
O(1)
Linked-list-based Stacks (cont’d)
template<class ItemType>
bool StackType<ItemType>::IsEmpty()
IsEmpty() const
{
return(topPtr == NULL);
}
template<class ItemType>
StackType<ItemType>::~StackType()
StackType()
{
MakeEmpty();
}
O(1)
O(N)
Linked-list-based Stacks (cont’d)
template<class ItemType>
bool StackType<ItemType>::IsFull()
IsFull() const
{
NodeType<ItemType>* location;
location = new NodeType<ItemType>; // test
if(location == NULL)
return true;
else {
delete location;
return false;
}
}
O(1)
Push (ItemType newItem)
• Function: Adds newItem to the top of
the stack.
• Preconditions: Stack has been
initialized and is not full.
• Postconditions: newItem is at the top
of the stack.
Pushing on a
non-empty
stack
Pushing on a non-empty stack
(cont.)
• The order of changing the pointers is
important!
Special Case: pushing on an
empty stack
Function Push
template <class ItemType>
void StackType<ItemType>::Push
Push(ItemType
item)
{
NodeType<ItemType>* location;
location = new NodeType<ItemType>;
location->info = newItem;
location->next = topPtr;
topPtr = location;
}
O(1)
Pop (ItemType& item)
• Function: Removes topItem from stack and
returns it in item.
• Preconditions: Stack has been initialized
and is not empty.
• Postconditions: Top element has been
removed from stack and item is a copy of
the removed element.
Popping the top element
Popping the top
element
(cont.)
Need a
temporary
pointer !
Special case: popping the last
element on the stack
tempPtr
Function Pop
template <class ItemType>
void StackType<ItemType>::Pop
Pop(ItemType& item)
{
NodeType<ItemType>* tempPtr;
item = topPtr->info;
tempPtr = topPtr;
topPtr = topPtr->next;
delete tempPtr;
}
O(1)
Comparing stack implementations
Big-O Comparison of Stack Operations
Operation Array
Implementation
Linked
Implementation
Constructor O(1) O(1)
MakeEmpty O(1) O(N)
IsFull O(1) O(1)
IsEmpty O(1) O(1)
Push O(1) O(1)
Pop O(1) O(1)
Destructor O(1) O(N)
Array-vs Linked-list-based
Stack Implementations
• Array-based implementation is simple but:
– The size of the stack must be determined when
a stack object is declared.
– Space is wasted if we use less elements.
– We cannot "enqueue" more elements than the
array can hold.
• Linked-list-based implementation alleviates
these problems but time requirements might
increase.
Example using stacks:
evaluate postfix expressions
• Postfix notation is another way of writing arithmetic
expressions.
• In postfix notation, the operator is written after the two
operands.
infix: 2+5 postfix: 2 5 +
• Why using postfix notation?
Precedence rules and parentheses are not required!
Example: postfix expressions
(cont.)
Expressions are evaluated from left to right.
Postfix expressions:
Algorithm using stacks (cont.)
Exercise 15: Write the body for a client function that
replaces each copy of an item in a stack with another item.
Use the following specification.
ReplaceItem(StackType& stack, ItemType oldItem,
ItemType newItem)
Function: Replaces all occurrences of oldItem with
newItem.
Precondition: stack has been initialized.
Postconditions: Each occurrence of oldItem in stack has
been replaced by newItem. Order of other elements remains
unchanged.
Warning: you may not assume any knowledge of how the
stack is implemented!
{
ItemType item;
StackType tempStack;
while (!Stack.IsEmpty()) {
Stack.Pop(item);
if (item==oldItem)
tempStack.Push(newItem);
else
tempStack.Push(item);
}
while (!tempStack.IsEmpty()) {
tempStack.Pop(item);
Stack.Push(item);
}
}
1
2
3
3
5
1
1
5
3
Stack
Stack
tempStack
oldItem = 2
newItem = 5
{
ItemType item;
StackType tempStack;
while (!Stack.IsEmpty()) {
Stack.Pop(item);
if (item==oldItem)
tempStack.Push(newItem);
else
tempStack.Push(item);
}
while (!tempStack.IsEmpty()) {
tempStack.Pop(item);
Stack.Push(item);
}
}
O(N)
What are the time
requirements using big-O?
Exercises 19, 20
Exercises 19, 20
Exercise 20
small large
Exercise 20 (cont’d)
etc.
Exercise 20 (cont’d)
Ad

More Related Content

Similar to Data Strcture and Algorithms - Destailed Analysis of Stacks (20)

Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming Introduction
Lou Loizides
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming Intro
Lou Loizides
 
CPP homework help
CPP homework helpCPP homework help
CPP homework help
C++ Homework Help
 
stacks and queues class 12 in c++
stacks and  queues class 12 in c++stacks and  queues class 12 in c++
stacks and queues class 12 in c++
Khushal Mehta
 
Templates2
Templates2Templates2
Templates2
zindadili
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
Michael Heron
 
STLStack.pdf
STLStack.pdfSTLStack.pdf
STLStack.pdf
rajaratna4
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Data structures and algorithms lab3
Data structures and algorithms lab3Data structures and algorithms lab3
Data structures and algorithms lab3
Bianca Teşilă
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
Dhaval Kaneria
 
02 stackqueue
02 stackqueue02 stackqueue
02 stackqueue
Chandan Kumar
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
stack in java ds - muhammed sdasdasdasdasdas.ppt
stack in java ds - muhammed sdasdasdasdasdas.pptstack in java ds - muhammed sdasdasdasdasdas.ppt
stack in java ds - muhammed sdasdasdasdasdas.ppt
ssusere3b1a2
 
TEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented ProgrammingTEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented Programming
208BVijaySunder
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
Muhazzab Chouhadry
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operation
Senthil Kumar
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
Kongunadu College of Engineering and Technology
 
2.1 STACK & QUEUE ADTS
2.1 STACK & QUEUE ADTS2.1 STACK & QUEUE ADTS
2.1 STACK & QUEUE ADTS
P. Subathra Kishore, KAMARAJ College of Engineering and Technology, Madurai
 
Developing a new Epsilon EMC driver
Developing a new Epsilon EMC driverDeveloping a new Epsilon EMC driver
Developing a new Epsilon EMC driver
Horacio Hoyos Rodríguez
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
MuskanSony
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming Introduction
Lou Loizides
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming Intro
Lou Loizides
 
stacks and queues class 12 in c++
stacks and  queues class 12 in c++stacks and  queues class 12 in c++
stacks and queues class 12 in c++
Khushal Mehta
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Data structures and algorithms lab3
Data structures and algorithms lab3Data structures and algorithms lab3
Data structures and algorithms lab3
Bianca Teşilă
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
Dhaval Kaneria
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
stack in java ds - muhammed sdasdasdasdasdas.ppt
stack in java ds - muhammed sdasdasdasdasdas.pptstack in java ds - muhammed sdasdasdasdasdas.ppt
stack in java ds - muhammed sdasdasdasdasdas.ppt
ssusere3b1a2
 
TEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented ProgrammingTEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented Programming
208BVijaySunder
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operation
Senthil Kumar
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
MuskanSony
 

Recently uploaded (20)

IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdfIBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
VigneshPalaniappanM
 
UNIT 3 Software Engineering (BCS601) EIOV.pdf
UNIT 3 Software Engineering (BCS601) EIOV.pdfUNIT 3 Software Engineering (BCS601) EIOV.pdf
UNIT 3 Software Engineering (BCS601) EIOV.pdf
sikarwaramit089
 
Urban Transport Infrastructure September 2023
Urban Transport Infrastructure September 2023Urban Transport Infrastructure September 2023
Urban Transport Infrastructure September 2023
Rajesh Prasad
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic AlgorithmDesign Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Journal of Soft Computing in Civil Engineering
 
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
Guru Nanak Technical Institutions
 
Modeling the Influence of Environmental Factors on Concrete Evaporation Rate
Modeling the Influence of Environmental Factors on Concrete Evaporation RateModeling the Influence of Environmental Factors on Concrete Evaporation Rate
Modeling the Influence of Environmental Factors on Concrete Evaporation Rate
Journal of Soft Computing in Civil Engineering
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
Optimizing Reinforced Concrete Cantilever Retaining Walls Using Gases Brownia...
Optimizing Reinforced Concrete Cantilever Retaining Walls Using Gases Brownia...Optimizing Reinforced Concrete Cantilever Retaining Walls Using Gases Brownia...
Optimizing Reinforced Concrete Cantilever Retaining Walls Using Gases Brownia...
Journal of Soft Computing in Civil Engineering
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
SanjeetMishra29
 
Automatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and BeyondAutomatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and Beyond
NU_I_TODALAB
 
DeFAIMint | 🤖Mint to DeFAI. Vibe Trading as NFT
DeFAIMint | 🤖Mint to DeFAI. Vibe Trading as NFTDeFAIMint | 🤖Mint to DeFAI. Vibe Trading as NFT
DeFAIMint | 🤖Mint to DeFAI. Vibe Trading as NFT
Kyohei Ito
 
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptxUnleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
SanjeetMishra29
 
IPC-7711D-7721D_ EN 2023 TOC Rework, Modification and Repair of Electronic As...
IPC-7711D-7721D_ EN 2023 TOC Rework, Modification and Repair of Electronic As...IPC-7711D-7721D_ EN 2023 TOC Rework, Modification and Repair of Electronic As...
IPC-7711D-7721D_ EN 2023 TOC Rework, Modification and Repair of Electronic As...
ssuserd9338b
 
Understand water laser communication using Arduino laser and solar panel
Understand water laser communication using Arduino laser and solar panelUnderstand water laser communication using Arduino laser and solar panel
Understand water laser communication using Arduino laser and solar panel
NaveenBotsa
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdfSmart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
PawachMetharattanara
 
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
PawachMetharattanara
 
IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdfIBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
IBAAS 2023 Series_Lecture 8- Dr. Nandi.pdf
VigneshPalaniappanM
 
UNIT 3 Software Engineering (BCS601) EIOV.pdf
UNIT 3 Software Engineering (BCS601) EIOV.pdfUNIT 3 Software Engineering (BCS601) EIOV.pdf
UNIT 3 Software Engineering (BCS601) EIOV.pdf
sikarwaramit089
 
Urban Transport Infrastructure September 2023
Urban Transport Infrastructure September 2023Urban Transport Infrastructure September 2023
Urban Transport Infrastructure September 2023
Rajesh Prasad
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
SanjeetMishra29
 
Automatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and BeyondAutomatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and Beyond
NU_I_TODALAB
 
DeFAIMint | 🤖Mint to DeFAI. Vibe Trading as NFT
DeFAIMint | 🤖Mint to DeFAI. Vibe Trading as NFTDeFAIMint | 🤖Mint to DeFAI. Vibe Trading as NFT
DeFAIMint | 🤖Mint to DeFAI. Vibe Trading as NFT
Kyohei Ito
 
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptxUnleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
Unleashing the Power of Salesforce Flows &amp_ Slack Integration!.pptx
SanjeetMishra29
 
IPC-7711D-7721D_ EN 2023 TOC Rework, Modification and Repair of Electronic As...
IPC-7711D-7721D_ EN 2023 TOC Rework, Modification and Repair of Electronic As...IPC-7711D-7721D_ EN 2023 TOC Rework, Modification and Repair of Electronic As...
IPC-7711D-7721D_ EN 2023 TOC Rework, Modification and Repair of Electronic As...
ssuserd9338b
 
Understand water laser communication using Arduino laser and solar panel
Understand water laser communication using Arduino laser and solar panelUnderstand water laser communication using Arduino laser and solar panel
Understand water laser communication using Arduino laser and solar panel
NaveenBotsa
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdfSmart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
PawachMetharattanara
 
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
PawachMetharattanara
 
Ad

Data Strcture and Algorithms - Destailed Analysis of Stacks

  • 1. Stacks CS 302 – Data Structures Sections 5.1, 5.2, 6.1, 6.5
  • 2. Warning • Although data structure concepts between this and last semesters will be the same, there might be implementation differences. • Your answers in questions in quizzes and exams should be based on this semester’s (CS302) implementations!
  • 3. Definitions • ImageType.h • ImageType.cpp • Driver.cpp class specification class implementation application (client code)
  • 4. Question • In object oriented programming, class implementation details are hidden from applications that use the class. • Why?
  • 5. What is a stack? • It is an ordered group of homogeneous items. • Items are added to and removed from the top of the stack LIFO property: Last In, First Out • The last item added would be the first to be removed TOP OF THE STACK TOP OF THE STACK
  • 7. Array-based Stacks template<class ItemType> class StackType { public: StackType(int); void MakeEmpty(); bool IsEmpty() const; bool IsFull() const; void Push(ItemType); void Pop(ItemType&); private: int top, maxStack; ItemType *items; }; dynamically allocated array
  • 8. Array-based Stacks (cont’d) template<class ItemType> StackType<ItemType>::StackType(int size) { top = -1; maxStack = size; items = new ItemType[max]; } template<class ItemType> StackType<ItemType>::~StackType() { delete [ ] items; } O(1) O(1)
  • 9. Array-based Stacks (cont’d) template<class ItemType> void StackType<ItemType>::MakeEmpty() { top = -1; } O(1)
  • 10. Array-based Stacks (cont.) template<class ItemType> bool StackType<ItemType>::IsEmpty() const { return (top == -1); } template<class ItemType> bool StackType<ItemType>::IsFull() const { return (top == maxStack-1); } O(1) O(1)
  • 11. Push (ItemType newItem) • Function: Adds newItem to the top of the stack. • Preconditions: Stack has been initialized and is not full. • Postconditions: newItem is at the top of the stack.
  • 12. Stack overflow • The condition resulting from trying to push an element onto a full stack. if(!stack.IsFull()) stack.Push(item);
  • 13. Array-based Stacks (cont.) template<class ItemType> void StackType<ItemType>::Push(ItemType newItem) { top++; items[top] = newItem; } O(1)
  • 14. Pop (ItemType& item) • Function: Removes topItem from stack and returns it in item. • Preconditions: Stack has been initialized and is not empty. • Postconditions: Top element has been removed from stack and item is a copy of the removed element.
  • 15. Stack underflow • The condition resulting from trying to pop an empty stack. if(!stack.IsEmpty()) stack.Pop(item);
  • 16. Array-based Stacks (cont.) template<class ItemType> void StackType<ItemType>::Pop(ItemType& item) { item = items[top]; top--; } O(1)
  • 17. Templates • Templates allow the compiler to generate multiple versions of a class type by allowing parameterized types. • Compiler generates distinct class types and gives its own internal name to each of the types.
  • 18. Compiling Templates • Cannot anymore compile StackType.cpp separately from the application of the class (e.g., driver.cpp) • Compiler needs to know the data type of the stack to instantiate the class! • Where can the compiler find this information?
  • 19. Compiling Templates (cont’d) // Client code StackType<int> myStack; StackType<float> yourStack; StackType<StrType> anotherStack; myStack.Push(35); yourStack.Push(584.39);
  • 20. Compiling Templates (cont’d) • Must compile StackType.cpp and client code (e.g., driver.cpp) together! (1) Use “include” directive to include StackType.cpp StackType.cpp at the end of StackType.h StackType.h (2) “include” StackType.h StackType.h in client’s code (3) Compile client code
  • 21. Linked-list-based Stacks template<class ItemType> struct NodeType<ItemType> { ItemType info; NodeType<ItemType>* next; };
  • 22. Linked-list-based Stacks (cont’d) template<class ItemType> struct NodeType<ItemType>; template<class ItemType> class StackType { public: StackType(); ~StackType(); void MakeEmpty(); bool IsEmpty() const; bool IsFull() const; void Push(ItemType); void Pop(ItemType&); private: NodeType<ItemType>* topPtr; };
  • 23. Linked-list-based Stacks (cont’d) template<class ItemType> StackType<ItemType>::StackType() StackType() { topPtr = NULL; } template<class ItemType> void StackType<ItemType>::MakeEmpty() MakeEmpty() { NodeType<ItemType>* tempPtr; while(topPtr != NULL) { tempPtr = topPtr; topPtr = topPtr->next; delete tempPtr; } } O(N) O(1)
  • 24. Linked-list-based Stacks (cont’d) template<class ItemType> bool StackType<ItemType>::IsEmpty() IsEmpty() const { return(topPtr == NULL); } template<class ItemType> StackType<ItemType>::~StackType() StackType() { MakeEmpty(); } O(1) O(N)
  • 25. Linked-list-based Stacks (cont’d) template<class ItemType> bool StackType<ItemType>::IsFull() IsFull() const { NodeType<ItemType>* location; location = new NodeType<ItemType>; // test if(location == NULL) return true; else { delete location; return false; } } O(1)
  • 26. Push (ItemType newItem) • Function: Adds newItem to the top of the stack. • Preconditions: Stack has been initialized and is not full. • Postconditions: newItem is at the top of the stack.
  • 28. Pushing on a non-empty stack (cont.) • The order of changing the pointers is important!
  • 29. Special Case: pushing on an empty stack
  • 30. Function Push template <class ItemType> void StackType<ItemType>::Push Push(ItemType item) { NodeType<ItemType>* location; location = new NodeType<ItemType>; location->info = newItem; location->next = topPtr; topPtr = location; } O(1)
  • 31. Pop (ItemType& item) • Function: Removes topItem from stack and returns it in item. • Preconditions: Stack has been initialized and is not empty. • Postconditions: Top element has been removed from stack and item is a copy of the removed element.
  • 32. Popping the top element
  • 33. Popping the top element (cont.) Need a temporary pointer !
  • 34. Special case: popping the last element on the stack tempPtr
  • 35. Function Pop template <class ItemType> void StackType<ItemType>::Pop Pop(ItemType& item) { NodeType<ItemType>* tempPtr; item = topPtr->info; tempPtr = topPtr; topPtr = topPtr->next; delete tempPtr; } O(1)
  • 36. Comparing stack implementations Big-O Comparison of Stack Operations Operation Array Implementation Linked Implementation Constructor O(1) O(1) MakeEmpty O(1) O(N) IsFull O(1) O(1) IsEmpty O(1) O(1) Push O(1) O(1) Pop O(1) O(1) Destructor O(1) O(N)
  • 37. Array-vs Linked-list-based Stack Implementations • Array-based implementation is simple but: – The size of the stack must be determined when a stack object is declared. – Space is wasted if we use less elements. – We cannot "enqueue" more elements than the array can hold. • Linked-list-based implementation alleviates these problems but time requirements might increase.
  • 38. Example using stacks: evaluate postfix expressions • Postfix notation is another way of writing arithmetic expressions. • In postfix notation, the operator is written after the two operands. infix: 2+5 postfix: 2 5 + • Why using postfix notation? Precedence rules and parentheses are not required!
  • 39. Example: postfix expressions (cont.) Expressions are evaluated from left to right.
  • 41. Exercise 15: Write the body for a client function that replaces each copy of an item in a stack with another item. Use the following specification. ReplaceItem(StackType& stack, ItemType oldItem, ItemType newItem) Function: Replaces all occurrences of oldItem with newItem. Precondition: stack has been initialized. Postconditions: Each occurrence of oldItem in stack has been replaced by newItem. Order of other elements remains unchanged. Warning: you may not assume any knowledge of how the stack is implemented!
  • 42. { ItemType item; StackType tempStack; while (!Stack.IsEmpty()) { Stack.Pop(item); if (item==oldItem) tempStack.Push(newItem); else tempStack.Push(item); } while (!tempStack.IsEmpty()) { tempStack.Pop(item); Stack.Push(item); } } 1 2 3 3 5 1 1 5 3 Stack Stack tempStack oldItem = 2 newItem = 5
  • 43. { ItemType item; StackType tempStack; while (!Stack.IsEmpty()) { Stack.Pop(item); if (item==oldItem) tempStack.Push(newItem); else tempStack.Push(item); } while (!tempStack.IsEmpty()) { tempStack.Pop(item); Stack.Push(item); } } O(N) What are the time requirements using big-O?