SlideShare a Scribd company logo
Chapter 3: Lists, Stacks, and
Queues - II
Text: Read Weiss, §3.6
1
The Stack ADT – Stack Model
•A stack (LIFO list) is a list with the restriction that
inserts and deletes can be performed in only one
position, namely the end of the list called the top.
•The two operations on a stack are push, pop (also top
to examine the item at the top). While pop on an empty
stack is generally considered an ADT error, running out
of space when performing a push is an implementation
error but not an ADT error.
2
3
• Since a stack is a list, any list implementation will do.
• Singly Linked List implementation of a stack: push by inserting at
the front, pop by deleting the element at the front.
• Array implementation of stack: It is the more popular solution. It uses
the InsertToBack and DeleteFromBack from the Vector
implementation. Associated with each stack is Array and
TopOfStack which is set to -1 for an empty stack.
Implementation of Stacks
#define Error(Str) FatalError(Str)
#define FatalError(Str) fprintf(stderr, "%sn", Str), exit(1)
#define EmptyTOS ( -1 )
#define MinStackSize ( 5 )
typedef int ElementType;
struct StackRecord {
int Capacity;
int TopOfStack;
ElementType *Array;
};
typedef struct StackRecord *Stack;
Array Implementation of Stacks - I
4
int IsEmpty( Stack S ){
return S->TopOfStack == EmptyTOS;
}
int IsFull( Stack S ){
return S->TopOfStack == S->Capacity - 1;
}
Stack CreateStack( int MaxElements ){
Stack S;
if(MaxElements<MinStackSize) Error("Stack size is too small");
S = malloc( sizeof( struct StackRecord ) );
if(S == NULL) FatalError("Out of space!!!");
S->Array = malloc(sizeof(ElementType)*MaxElements);
if(S->Array == NULL) FatalError("Out of space!!!");
S->Capacity = MaxElements;
MakeEmpty(S);
return S;
}
5
Array Implementation of Stacks - II
void MakeEmpty(Stack S){
S->TopOfStack = EmptyTOS;
}
void DisposeStack(Stack S){
if( S != NULL ){
free( S->Array );
free( S );
}
}
void Push(ElementType X, Stack S){
if( IsFull( S ) )
Error( "Full stack" );
else
S->Array[ ++S->TopOfStack ] = X;
}
void Pop( Stack S ){
if( IsEmpty( S ) )
Error( "Empty stack" );
else
S->TopOfStack--;
}
ElementType Top( Stack S ){ /* TopandPop is similar */
if( !IsEmpty( S ) )
return S->Array[ S->TopOfStack ];
Error( "Empty stack" );
return 0; /* Return value used to avoid warning */
}
6
Stack Applications - Balancing Symbols
• Compilers check programs
for syntax errors, but
frequently a lack of one
symbol (such as a missing
brace or comment starter)
will cause the compiler to
spill out a hundred lines of
diagnostics. Thus, every
right brace, bracket, and
parenthesis must
correspond to their left
counterparts.
• Example: The sequence
[()] is legal, but [(]) is not.
stack Ø;
while (!eof(file)){
read(char);
if (isOpening(char))
push(char, stack);
else if (isClosing(char))
if (isEmpty(stack)
error();
else
cchar = topAndPop(stack);
if (!isMatching(char,cchar))
error();
}
if (!isEmpty(stack))
error();
It is clearly linear and actually makes
only one pass through the input. It is
thus on-line and quite fast.
Stack Applications – Postfix
Expressions
• Order of evaluation for arithmetic expressions
depending on the precedence and associativity of
operators has a huge impact on the result of the
evaluation.
• Example: 4.99 + 5.99 + 6.99 * 1.06 = produces either
19.05, or 18.39. Most simple four-function calculators
will give the first answer, but better calculators know
that multiplication has higher precedence than addition.
• A scientific calculator generally comes with
parentheses, so we can always get the right answer by
parenthesizing, but with a simple calculator we need to
remember intermediate results.
7
Postfix Notation
• (((a*b)+c)+(d*e)) fully parenthesized
• T1=a*b, T1=T1+c, T2=d*e, T1=T1+T2 by
using intermediate results
• a b * c + d e * + is the equivalent of using
intermediate results. This notation is
known as postfix or reverse Polish
notation.
• Notice that when an expression is given in
postfix notation, there is no need to know
any precedence rules.
8
Postfix Expression Evaluation
9
6 5 2 3 + 8 * + 3 + *
First four symbols are
placed on the stack.
+ 8 * + 3 + * 8 * + 3 + * * + 3 + * + 3 + *
3 + * + * *
This algorithm
depicted below
is clearly O(N)
Infix to Postfix Conversion
• We can use stacks to convert an
expression in standart form (otherwise
known as infix) into postfix.
• Example: operators = {+, *, (, )}, usual
precedence rules; a + b * c + (d * e + f) * g
Answer = a b c * + d e * f + g * +
10
Infix to Postfix - Algorithm
11
stack Ø;
while (! eos(expr)){
read(char);
if (isOperand(char))
output(char);
else if (char == “)”)
while ((!isEmpty(stack))&&((sc=topAndPop(stack))!= “(”))
output(sc);
else
while ( (!isEmpty(stack)) &&
(inStackPriority(top(stack))>=(outStackPriority(char))))
output(topAndPop(stack));
push(char, stack);
}
while (!isEmpty(stack))
output(topAndpop(stack));
inStackPriority(“(”)=very low outStackPriority(“(”)=very high
inStackPriority outStackPriority
** (RL) 4 5
*, / (LR) 3 3
+, - (LR) 2 2
( 1 6
Infix to Postfix – Example I
12
• * c + (d * e + f) * g
• + (d * e + f) * g
• (d * e + f) * g
• * e + f) * g
• a + b * c + (d * e + f) * g
Infix to Postfix – Example II
13
• + f) * g
• ) * g
• * g
Function Calls
• The algorithm to check balanced symbols suggests a way to
implement function calls.
• The problem here is that when a call is made to a new
function, all the variables local to the calling routine need to be
saved by the system.
• Furthermore, the current location in the routine must be saved
so that the new function knows where to go after it is done.
• “(“ and “)” are exactly like function call and function return.
• Every PL implementing recursion has that mechanism. The
information saved is called either an activation record or
stack frame. There is always the possibility that you will run
out of stack space by having too many simultaneously active
functions. On many systems there is no checking for overflow.
14
Function Calls and Recursion
• The routine print_list printing out a linked list, is perfectly legal
and actually correct. It properly handles the base case of an
empty list, and the recursion is fine. Unfortunately, if the list
contains 20,000 elements, there will be a stack of 20,000
activation records (and hence possibly a program crash).
• An example of an extremely bad use of recursion known as
tail recursion (recursive call at the last line). It can be
automatically eliminated by enclosing the body in a while loop
and replacing the recursive call with one assignment per
function argument.
15
void print_list( LIST L ) {
if( L != NULL ) {
print_element(L->element);
print_list( L->next );
}
}
void print_list( LIST L ){
while (1) {
if( L != NULL ){
print_element(L->element);
L = L->next;
}
}
}

More Related Content

What's hot

stack presentation
stack presentationstack presentation
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
Ssankett Negi
 
DATA STRUCTURE - STACK
DATA STRUCTURE - STACKDATA STRUCTURE - STACK
DATA STRUCTURE - STACK
Devyani Chaudhari
 
Stacks and queue
Stacks and queueStacks and queue
Stacks and queue
Amit Vats
 
Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]
Muhammad Hammad Waseem
 
Application of Stack - Yadraj Meena
Application of Stack - Yadraj MeenaApplication of Stack - Yadraj Meena
Application of Stack - Yadraj Meena
Dipayan Sarkar
 
Stack
StackStack
Stack and its operations
Stack and its operationsStack and its operations
Stack and its operations
V.V.Vanniaperumal College for Women
 
Stack data structure
Stack data structureStack data structure
Stack data structure
Tech_MX
 
Stack
StackStack
Stack and queue
Stack and queueStack and queue
Stack and queue
Katang Isip
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
Dabbal Singh Mahara
 
Stack Operation In Data Structure
Stack Operation In Data Structure Stack Operation In Data Structure
Stack Operation In Data Structure
DivyeshKumar Jagatiya
 
Stack queue
Stack queueStack queue
Stack queue
Harry Potter
 
Stacks, Queues, Deques
Stacks, Queues, DequesStacks, Queues, Deques
Stacks, Queues, Deques
A-Tech and Software Development
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
Ashim Lamichhane
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
Muhazzab Chouhadry
 
Stack
StackStack
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
Soumen Santra
 

What's hot (19)

stack presentation
stack presentationstack presentation
stack presentation
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
 
DATA STRUCTURE - STACK
DATA STRUCTURE - STACKDATA STRUCTURE - STACK
DATA STRUCTURE - STACK
 
Stacks and queue
Stacks and queueStacks and queue
Stacks and queue
 
Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]
 
Application of Stack - Yadraj Meena
Application of Stack - Yadraj MeenaApplication of Stack - Yadraj Meena
Application of Stack - Yadraj Meena
 
Stack
StackStack
Stack
 
Stack and its operations
Stack and its operationsStack and its operations
Stack and its operations
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Stack
StackStack
Stack
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
 
Stack Operation In Data Structure
Stack Operation In Data Structure Stack Operation In Data Structure
Stack Operation In Data Structure
 
Stack queue
Stack queueStack queue
Stack queue
 
Stacks, Queues, Deques
Stacks, Queues, DequesStacks, Queues, Deques
Stacks, Queues, Deques
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
 
Stack
StackStack
Stack
 
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
 

Similar to 5 chapter3 list_stackqueuepart2

lecture10trsgfchjvxgfzfdchgdchgcgshyjh.ppt
lecture10trsgfchjvxgfzfdchgdchgcgshyjh.pptlecture10trsgfchjvxgfzfdchgdchgcgshyjh.ppt
lecture10trsgfchjvxgfzfdchgdchgcgshyjh.ppt
partho5958
 
5.-Stacks.pptx
5.-Stacks.pptx5.-Stacks.pptx
5.-Stacks.pptx
iloveyoucarlo0923
 
stack.ppt
stack.pptstack.ppt
stack.ppt
ssuserec1395
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
chandankumar364348
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURES
Usha Mahalingam
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
KALPANAC20
 
358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9
sumitbardhan
 
Stack linked list
Stack linked listStack linked list
Stack linked list
bhargav0077
 
Stacks
StacksStacks
Stacks
sweta dargad
 
Stack
StackStack
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
nikshaikh786
 
Stack and its operations, Queue and its operations
Stack and its operations, Queue and its operationsStack and its operations, Queue and its operations
Stack and its operations, Queue and its operations
poongothai11
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptx
line24arts
 
Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7
Kumar
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
Apurbo Datta
 
Stack - Data Structure - Notes
Stack - Data Structure - NotesStack - Data Structure - Notes
Stack - Data Structure - Notes
Omprakash Chauhan
 
STACK1.pptx
STACK1.pptxSTACK1.pptx
STACK1.pptx
MouDhara1
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo
JinTaek Seo
 
2 a stacks
2 a stacks2 a stacks
2 a stacks
Nguync91368
 
computer notes - Data Structures - 8
computer notes - Data Structures - 8computer notes - Data Structures - 8
computer notes - Data Structures - 8
ecomputernotes
 

Similar to 5 chapter3 list_stackqueuepart2 (20)

lecture10trsgfchjvxgfzfdchgdchgcgshyjh.ppt
lecture10trsgfchjvxgfzfdchgdchgcgshyjh.pptlecture10trsgfchjvxgfzfdchgdchgcgshyjh.ppt
lecture10trsgfchjvxgfzfdchgdchgcgshyjh.ppt
 
5.-Stacks.pptx
5.-Stacks.pptx5.-Stacks.pptx
5.-Stacks.pptx
 
stack.ppt
stack.pptstack.ppt
stack.ppt
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURES
 
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
 
358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9
 
Stack linked list
Stack linked listStack linked list
Stack linked list
 
Stacks
StacksStacks
Stacks
 
Stack
StackStack
Stack
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Stack and its operations, Queue and its operations
Stack and its operations, Queue and its operationsStack and its operations, Queue and its operations
Stack and its operations, Queue and its operations
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptx
 
Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Stack - Data Structure - Notes
Stack - Data Structure - NotesStack - Data Structure - Notes
Stack - Data Structure - Notes
 
STACK1.pptx
STACK1.pptxSTACK1.pptx
STACK1.pptx
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo
 
2 a stacks
2 a stacks2 a stacks
2 a stacks
 
computer notes - Data Structures - 8
computer notes - Data Structures - 8computer notes - Data Structures - 8
computer notes - Data Structures - 8
 

More from SSE_AndyLi

Chapter 07 Digital Alrithmetic and Arithmetic Circuits
Chapter 07 Digital Alrithmetic and Arithmetic CircuitsChapter 07 Digital Alrithmetic and Arithmetic Circuits
Chapter 07 Digital Alrithmetic and Arithmetic Circuits
SSE_AndyLi
 
Chapter 06 Combinational Logic Functions
Chapter 06 Combinational Logic FunctionsChapter 06 Combinational Logic Functions
Chapter 06 Combinational Logic Functions
SSE_AndyLi
 
Chapter 5 introduction to VHDL
Chapter 5 introduction to VHDLChapter 5 introduction to VHDL
Chapter 5 introduction to VHDL
SSE_AndyLi
 
Chapter 03 Boolean Algebra and Combinational Logic
Chapter 03 Boolean Algebra and Combinational LogicChapter 03 Boolean Algebra and Combinational Logic
Chapter 03 Boolean Algebra and Combinational Logic
SSE_AndyLi
 
Chapter 02 Logic Functions and Gates
Chapter 02 Logic Functions and GatesChapter 02 Logic Functions and Gates
Chapter 02 Logic Functions and Gates
SSE_AndyLi
 
Chapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital SystemsChapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital Systems
SSE_AndyLi
 
15 chapter9 graph_algorithms_mst
15 chapter9 graph_algorithms_mst15 chapter9 graph_algorithms_mst
15 chapter9 graph_algorithms_mst
SSE_AndyLi
 
14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpath14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpath
SSE_AndyLi
 
10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queues10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queues
SSE_AndyLi
 
9 chapter4 trees_avl
9 chapter4 trees_avl9 chapter4 trees_avl
9 chapter4 trees_avl
SSE_AndyLi
 
8 chapter4 trees_bst
8 chapter4 trees_bst8 chapter4 trees_bst
8 chapter4 trees_bst
SSE_AndyLi
 
7 chapter4 trees_binary
7 chapter4 trees_binary7 chapter4 trees_binary
7 chapter4 trees_binary
SSE_AndyLi
 
6 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart36 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart3
SSE_AndyLi
 
4 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart14 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart1
SSE_AndyLi
 
3 chapter2 algorithm_analysispart2
3 chapter2 algorithm_analysispart23 chapter2 algorithm_analysispart2
3 chapter2 algorithm_analysispart2
SSE_AndyLi
 
2 chapter2 algorithm_analysispart1
2 chapter2 algorithm_analysispart12 chapter2 algorithm_analysispart1
2 chapter2 algorithm_analysispart1
SSE_AndyLi
 
1 chapter1 introduction
1 chapter1 introduction1 chapter1 introduction
1 chapter1 introduction
SSE_AndyLi
 

More from SSE_AndyLi (17)

Chapter 07 Digital Alrithmetic and Arithmetic Circuits
Chapter 07 Digital Alrithmetic and Arithmetic CircuitsChapter 07 Digital Alrithmetic and Arithmetic Circuits
Chapter 07 Digital Alrithmetic and Arithmetic Circuits
 
Chapter 06 Combinational Logic Functions
Chapter 06 Combinational Logic FunctionsChapter 06 Combinational Logic Functions
Chapter 06 Combinational Logic Functions
 
Chapter 5 introduction to VHDL
Chapter 5 introduction to VHDLChapter 5 introduction to VHDL
Chapter 5 introduction to VHDL
 
Chapter 03 Boolean Algebra and Combinational Logic
Chapter 03 Boolean Algebra and Combinational LogicChapter 03 Boolean Algebra and Combinational Logic
Chapter 03 Boolean Algebra and Combinational Logic
 
Chapter 02 Logic Functions and Gates
Chapter 02 Logic Functions and GatesChapter 02 Logic Functions and Gates
Chapter 02 Logic Functions and Gates
 
Chapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital SystemsChapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital Systems
 
15 chapter9 graph_algorithms_mst
15 chapter9 graph_algorithms_mst15 chapter9 graph_algorithms_mst
15 chapter9 graph_algorithms_mst
 
14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpath14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpath
 
10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queues10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queues
 
9 chapter4 trees_avl
9 chapter4 trees_avl9 chapter4 trees_avl
9 chapter4 trees_avl
 
8 chapter4 trees_bst
8 chapter4 trees_bst8 chapter4 trees_bst
8 chapter4 trees_bst
 
7 chapter4 trees_binary
7 chapter4 trees_binary7 chapter4 trees_binary
7 chapter4 trees_binary
 
6 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart36 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart3
 
4 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart14 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart1
 
3 chapter2 algorithm_analysispart2
3 chapter2 algorithm_analysispart23 chapter2 algorithm_analysispart2
3 chapter2 algorithm_analysispart2
 
2 chapter2 algorithm_analysispart1
2 chapter2 algorithm_analysispart12 chapter2 algorithm_analysispart1
2 chapter2 algorithm_analysispart1
 
1 chapter1 introduction
1 chapter1 introduction1 chapter1 introduction
1 chapter1 introduction
 

Recently uploaded

E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
Requirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional SafetyRequirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional Safety
Ayan Halder
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative AnalysisOdoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Envertis Software Solutions
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
aymanquadri279
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
Yara Milbes
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
Peter Muessig
 

Recently uploaded (20)

E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
Requirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional SafetyRequirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional Safety
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative AnalysisOdoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
 

5 chapter3 list_stackqueuepart2

  • 1. Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1
  • 2. The Stack ADT – Stack Model •A stack (LIFO list) is a list with the restriction that inserts and deletes can be performed in only one position, namely the end of the list called the top. •The two operations on a stack are push, pop (also top to examine the item at the top). While pop on an empty stack is generally considered an ADT error, running out of space when performing a push is an implementation error but not an ADT error. 2
  • 3. 3 • Since a stack is a list, any list implementation will do. • Singly Linked List implementation of a stack: push by inserting at the front, pop by deleting the element at the front. • Array implementation of stack: It is the more popular solution. It uses the InsertToBack and DeleteFromBack from the Vector implementation. Associated with each stack is Array and TopOfStack which is set to -1 for an empty stack. Implementation of Stacks #define Error(Str) FatalError(Str) #define FatalError(Str) fprintf(stderr, "%sn", Str), exit(1) #define EmptyTOS ( -1 ) #define MinStackSize ( 5 ) typedef int ElementType; struct StackRecord { int Capacity; int TopOfStack; ElementType *Array; }; typedef struct StackRecord *Stack;
  • 4. Array Implementation of Stacks - I 4 int IsEmpty( Stack S ){ return S->TopOfStack == EmptyTOS; } int IsFull( Stack S ){ return S->TopOfStack == S->Capacity - 1; } Stack CreateStack( int MaxElements ){ Stack S; if(MaxElements<MinStackSize) Error("Stack size is too small"); S = malloc( sizeof( struct StackRecord ) ); if(S == NULL) FatalError("Out of space!!!"); S->Array = malloc(sizeof(ElementType)*MaxElements); if(S->Array == NULL) FatalError("Out of space!!!"); S->Capacity = MaxElements; MakeEmpty(S); return S; }
  • 5. 5 Array Implementation of Stacks - II void MakeEmpty(Stack S){ S->TopOfStack = EmptyTOS; } void DisposeStack(Stack S){ if( S != NULL ){ free( S->Array ); free( S ); } } void Push(ElementType X, Stack S){ if( IsFull( S ) ) Error( "Full stack" ); else S->Array[ ++S->TopOfStack ] = X; } void Pop( Stack S ){ if( IsEmpty( S ) ) Error( "Empty stack" ); else S->TopOfStack--; } ElementType Top( Stack S ){ /* TopandPop is similar */ if( !IsEmpty( S ) ) return S->Array[ S->TopOfStack ]; Error( "Empty stack" ); return 0; /* Return value used to avoid warning */ }
  • 6. 6 Stack Applications - Balancing Symbols • Compilers check programs for syntax errors, but frequently a lack of one symbol (such as a missing brace or comment starter) will cause the compiler to spill out a hundred lines of diagnostics. Thus, every right brace, bracket, and parenthesis must correspond to their left counterparts. • Example: The sequence [()] is legal, but [(]) is not. stack Ø; while (!eof(file)){ read(char); if (isOpening(char)) push(char, stack); else if (isClosing(char)) if (isEmpty(stack) error(); else cchar = topAndPop(stack); if (!isMatching(char,cchar)) error(); } if (!isEmpty(stack)) error(); It is clearly linear and actually makes only one pass through the input. It is thus on-line and quite fast.
  • 7. Stack Applications – Postfix Expressions • Order of evaluation for arithmetic expressions depending on the precedence and associativity of operators has a huge impact on the result of the evaluation. • Example: 4.99 + 5.99 + 6.99 * 1.06 = produces either 19.05, or 18.39. Most simple four-function calculators will give the first answer, but better calculators know that multiplication has higher precedence than addition. • A scientific calculator generally comes with parentheses, so we can always get the right answer by parenthesizing, but with a simple calculator we need to remember intermediate results. 7
  • 8. Postfix Notation • (((a*b)+c)+(d*e)) fully parenthesized • T1=a*b, T1=T1+c, T2=d*e, T1=T1+T2 by using intermediate results • a b * c + d e * + is the equivalent of using intermediate results. This notation is known as postfix or reverse Polish notation. • Notice that when an expression is given in postfix notation, there is no need to know any precedence rules. 8
  • 9. Postfix Expression Evaluation 9 6 5 2 3 + 8 * + 3 + * First four symbols are placed on the stack. + 8 * + 3 + * 8 * + 3 + * * + 3 + * + 3 + * 3 + * + * * This algorithm depicted below is clearly O(N)
  • 10. Infix to Postfix Conversion • We can use stacks to convert an expression in standart form (otherwise known as infix) into postfix. • Example: operators = {+, *, (, )}, usual precedence rules; a + b * c + (d * e + f) * g Answer = a b c * + d e * f + g * + 10
  • 11. Infix to Postfix - Algorithm 11 stack Ø; while (! eos(expr)){ read(char); if (isOperand(char)) output(char); else if (char == “)”) while ((!isEmpty(stack))&&((sc=topAndPop(stack))!= “(”)) output(sc); else while ( (!isEmpty(stack)) && (inStackPriority(top(stack))>=(outStackPriority(char)))) output(topAndPop(stack)); push(char, stack); } while (!isEmpty(stack)) output(topAndpop(stack)); inStackPriority(“(”)=very low outStackPriority(“(”)=very high inStackPriority outStackPriority ** (RL) 4 5 *, / (LR) 3 3 +, - (LR) 2 2 ( 1 6
  • 12. Infix to Postfix – Example I 12 • * c + (d * e + f) * g • + (d * e + f) * g • (d * e + f) * g • * e + f) * g • a + b * c + (d * e + f) * g
  • 13. Infix to Postfix – Example II 13 • + f) * g • ) * g • * g
  • 14. Function Calls • The algorithm to check balanced symbols suggests a way to implement function calls. • The problem here is that when a call is made to a new function, all the variables local to the calling routine need to be saved by the system. • Furthermore, the current location in the routine must be saved so that the new function knows where to go after it is done. • “(“ and “)” are exactly like function call and function return. • Every PL implementing recursion has that mechanism. The information saved is called either an activation record or stack frame. There is always the possibility that you will run out of stack space by having too many simultaneously active functions. On many systems there is no checking for overflow. 14
  • 15. Function Calls and Recursion • The routine print_list printing out a linked list, is perfectly legal and actually correct. It properly handles the base case of an empty list, and the recursion is fine. Unfortunately, if the list contains 20,000 elements, there will be a stack of 20,000 activation records (and hence possibly a program crash). • An example of an extremely bad use of recursion known as tail recursion (recursive call at the last line). It can be automatically eliminated by enclosing the body in a while loop and replacing the recursive call with one assignment per function argument. 15 void print_list( LIST L ) { if( L != NULL ) { print_element(L->element); print_list( L->next ); } } void print_list( LIST L ){ while (1) { if( L != NULL ){ print_element(L->element); L = L->next; } } }