SlideShare a Scribd company logo
1 of 26
Chapter 6
Stacks
Dr. Muhammad Hanif Durad
Department of Computer and Information Sciences
Pakistan Institute Engineering and Applied Sciences
hanif@pieas.edu.pk
Some slides have bee adapted with thanks from some other lectures
available on Internet. It made my life easier, as life is always
miserable at PIEAS (Sir Muhammad Yusaf Kakakhil )
Dr. Hanif Durad 2
Lecture Outline
 Introduction
 Stack
 Stack operations
 Implementation of Stacks
 Arrays
 Linked lists
 Applications of Stack
Introduction
 Stack
 The element deleted from the set is the one
most recently inserted
 Last-in, First-out (LIFO)
D:DSAL5165 Advanced Algorithm and Programming Languageunit09.ppt
Introduction
 Stack operations
 PUSH: Insert
 POP: Delete
 TOP: return the key value of the most recently
inserted element
 STACK-EMPTY: check if the stack is empty
 STACK-FULL: check if the stack is full
An Example of Stack
2
8
1
7
2
7
2
1
7
2
1
7
2
8
1
7
2
8
1
7
2
top
top
top
top
top
top
Push(8) Push(2)
pop(2)
pop(8)pop(1)
D:Data StructuresICS202Lecture10.ppt
Implementation of Stacks
 Any list implementation could be used to
implement a stack
 Arrays (static: the size of stack is given initially)
 Linked lists (dynamic: never become full)
 We will explore implementations based on array
and linked list
 Let’s see how to use an array to implement a
stack first
Represent Stack by Array
 A stack of at most n elements can be implemented by an array
S[1..n]
 top[S]: a pointer to the most recently inserted element
 A stack consists of elements S[1..top[S]]
 S[1]: the element at the bottom of the stack
 S[top[S]]: the element at the top
Stack Operations
How to implement
TOP(S), STACK-FULL(S) ?
O(1)
Illustration of PUSH
15 6 2 9S
top[S]=4
PUSH(S, 17)
15 6 2 9S
top[S]=4
top[S]=5
top[S]  top[S] + 1 (top[S] = 5)
S[top[S]]  x (S[5] = 17)
17
Illustration of POP
15 6 2 9 17 3S
top[S]=6
POP(S)
15 6 2 9 17 3S
top[S]=6
top[S]=5
top[S]  top[S] - 1 (top[S] = 5)
return S[top[S]+1] (return S[6])
3
11
 Nodes (data, pointer) connected in a chain by links
 the head or the tail of the list could serve as the top of
the stack
Linked List Implementation
D:Data StructuresHanif_SearchQueuesad5.ppt
Applications of Stack
Dr. Hanif Durad 12
Applications of Stack
 Direct applications
 Parenthesis matching
 Polish postfix and prefix notations
 Expression evaluations
 Undo sequence in a text editor
 Handling function calls and return
 Handling recursion
 Indirect applications
 Auxiliary data structure for algorithms
 Component of other data structures
+++ many more
Parenthesis Matching (1/2)
 To check that every right brace, bracket, and
parentheses must correspond to its left
counterpart
 e.g. [( )] is legal, but [( ] ) is illegal
Dr. Hanif Durad 14
D:Data StructuresHanif_SearchStacks stack-queue.ppt,P-18/44
Parenthesis Matching (2/2)
 Algorithm
(1) Make an empty stack.
(2) Read characters until end of file
i. If the character is an opening symbol, push it onto the stack
ii. If it is a closing symbol, then if the stack is empty, report an
error
iii. Otherwise, pop the stack. If the symbol popped is not the
corresponding opening symbol, then report an error
(3) At end of file, if the stack is not empty, report an err
Dr. Hanif Durad 15
Parenthesis Matching Example
Dr. Hanif Durad 16
D:Data StructuresHanif_SearchStacks
Example: On board. DS1, P-185
17
RPN or Postfix Notation
 Most compilers convert an expression in infix
notation to postfix
 the operators are written after the operands
 So a * b + c becomes a b * c +
 Advantage:
 expressions can be written without parentheses
chapter07.ppt
18
Postfix and Prefix Examples
INFIX RPN (POSTFIX) PREFIX
A + B
A * B + C
A * (B + C)
A - (B - (C - D))
A - B - C - D
* A + B C
+ * A B C
-A-B-C D
---A B C D
+ A B
Prefix : Operators come before
the operands
A B +
A B * C +
A B C + *
A B C D---
A B-C-D-
Algorithm for Infix to Postfix
1) Examine the next element in the input.
2) If it is operand, output it.
3) If it is opening parenthesis, push it on stack.
4) If it is an operator, then
i) If stack is empty, push operator on stack.
ii) If the top of stack is opening parenthesis, push operator on stack
iii) If it has higher priority than the top of stack, push operator on
stack.
iv) Else pop the operator from the stack and output it, repeat step 4
5) If it is a closing parenthesis, pop operators from stack and output
them until an opening parenthesis is encountered. pop and discard
the opening parenthesis.
6) If there is more input go to step 1
7) If there is no more input, pop the remaining operators to output.
Lecture 10,11 Stacks.pptx
Suppose we want to convert 2*3/(2-1)+5*3 into Postfix form,
So, the Postfix Expression is 23*21-/53*+
2 Empty 2
* * 2
3 * 23
/ / 23*
( /( 23*
2 /( 23*2
- /(- 23*2
1 /(- 23*21
) / 23*21-
+ + 23*21-/
5 + 23*21-/5
3 +* 23*21-/53
Expression Stack Output
* +* 23*21-/53
Empty 23*21-/53*+
Evaluation a postfix expression
• Each operator in a postfix string refers to the
previous two operands in the string.
• Suppose that each time we read an operand we
push it into a stack. When we reach an operator,
its operands will then be top two elements on the
stack
• We can then pop these two elements, perform the
indicated operation on them, and push the result
on the stack.
• So that it will be available for use as an operand of
the next operator.
Evaluating Postfix Notation
• Use a stack to evaluate an expression
in postfix notation.
• The postfix expression to be evaluated
is scanned from left to right.
• Variables or constants are pushed onto
the stack.
• When an operator is encountered, the
indicated action is performed using the
top elements of the stack, and the result
replaces the operands on the stack.
Evaluating a postfix expression
• Initialise an empty stack
• While token remain in the input stream
–Read next token
–If token is a number, push it into the stack
–Else, if token is an operator, pop top two
tokens off the stack,apply the operator, and
push the answer back into the stack
• Pop the answer off the stack.
Example: postfix expressions
(cont.)
Postfix expressions:
Algorithm using stacks (cont.)
Function calls
 Programming languages use stacks to keep track of
function calls
 When a function call occurs
 Push CPU registers and program counter on to stack
(“activation record” or “stack frame”)
 Upon return, restore registers and program counter from
top stack frame and pop
Dr. Hanif Durad 26
D:Data StructuresCPT S 223adt.ppt, P-47/52

More Related Content

What's hot

stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for publiciqbalphy1
 
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-9sumitbardhan
 
Presentation on Elementary data structures
Presentation on Elementary data structuresPresentation on Elementary data structures
Presentation on Elementary data structuresKuber Chandra
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operationSenthil Kumar
 
Stack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi LecturerStack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi Lecturergomathi chlm
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsHoang Nguyen
 
Stack data structure in Data Structure using C
Stack data structure in Data Structure using C Stack data structure in Data Structure using C
Stack data structure in Data Structure using C Meghaj Mallick
 
UNIT II LINEAR DATA STRUCTURES – STACKS, QUEUES
UNIT II 	LINEAR DATA STRUCTURES – STACKS, QUEUES	UNIT II 	LINEAR DATA STRUCTURES – STACKS, QUEUES
UNIT II LINEAR DATA STRUCTURES – STACKS, QUEUES Kathirvel Ayyaswamy
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queuestech4us
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1smruti sarangi
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJulie Iskander
 
هياكلبيانات
هياكلبياناتهياكلبيانات
هياكلبياناتRafal Edward
 
Queue data structure
Queue data structureQueue data structure
Queue data structureanooppjoseph
 
Module 01 Stack and Recursion
Module 01 Stack and RecursionModule 01 Stack and Recursion
Module 01 Stack and RecursionTushar B Kute
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data StructureSriram Raj
 

What's hot (20)

Data structure stack&queue basics
Data structure stack&queue   basicsData structure stack&queue   basics
Data structure stack&queue basics
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for public
 
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
 
stacks and queues
stacks and queuesstacks and queues
stacks and queues
 
Presentation on Elementary data structures
Presentation on Elementary data structuresPresentation on Elementary data structures
Presentation on Elementary data structures
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operation
 
Stack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi LecturerStack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi Lecturer
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Stack data structure in Data Structure using C
Stack data structure in Data Structure using C Stack data structure in Data Structure using C
Stack data structure in Data Structure using C
 
UNIT II LINEAR DATA STRUCTURES – STACKS, QUEUES
UNIT II 	LINEAR DATA STRUCTURES – STACKS, QUEUES	UNIT II 	LINEAR DATA STRUCTURES – STACKS, QUEUES
UNIT II LINEAR DATA STRUCTURES – STACKS, QUEUES
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queues
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Data structures
Data structuresData structures
Data structures
 
هياكلبيانات
هياكلبياناتهياكلبيانات
هياكلبيانات
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Module 01 Stack and Recursion
Module 01 Stack and RecursionModule 01 Stack and Recursion
Module 01 Stack and Recursion
 
02 Stack
02 Stack02 Stack
02 Stack
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 

Similar to Chapter 6 ds

Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxchandankumar364348
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manualnikshaikh786
 
Concept of stack ,stack of aaray stack by linked list , application of stac...
Concept of stack ,stack of aaray   stack by linked list , application of stac...Concept of stack ,stack of aaray   stack by linked list , application of stac...
Concept of stack ,stack of aaray stack by linked list , application of stac...muskankumari7360
 
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptxApplication of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptxPrakash Zodge
 
Unit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxUnit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxYogesh Pawar
 
Infix-Postfix expression conversion
Infix-Postfix expression conversionInfix-Postfix expression conversion
Infix-Postfix expression conversionRashmiranja625
 
Advanced data structures slide 2 2+
Advanced data structures slide 2 2+Advanced data structures slide 2 2+
Advanced data structures slide 2 2+jomerson remorosa
 
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 ADTSoumen Santra
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptxline24arts
 
Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Getachew Ganfur
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxhaaamin01
 
ADT STACK and Queues
ADT STACK and QueuesADT STACK and Queues
ADT STACK and QueuesBHARATH KUMAR
 
Stack application
Stack applicationStack application
Stack applicationStudent
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seoJinTaek Seo
 

Similar to Chapter 6 ds (20)

CH4.pptx
CH4.pptxCH4.pptx
CH4.pptx
 
DS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptxDS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptx
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Concept of stack ,stack of aaray stack by linked list , application of stac...
Concept of stack ,stack of aaray   stack by linked list , application of stac...Concept of stack ,stack of aaray   stack by linked list , application of stac...
Concept of stack ,stack of aaray stack by linked list , application of stac...
 
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptxApplication of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
 
Unit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxUnit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptx
 
Infix-Postfix expression conversion
Infix-Postfix expression conversionInfix-Postfix expression conversion
Infix-Postfix expression conversion
 
Stack
StackStack
Stack
 
Advanced data structures slide 2 2+
Advanced data structures slide 2 2+Advanced data structures slide 2 2+
Advanced data structures slide 2 2+
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 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
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptx
 
Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9
 
Rana Junaid Rasheed
Rana Junaid RasheedRana Junaid Rasheed
Rana Junaid Rasheed
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptx
 
ADT STACK and Queues
ADT STACK and QueuesADT STACK and Queues
ADT STACK and Queues
 
Stack application
Stack applicationStack application
Stack application
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo
 

More from Hanif Durad

More from Hanif Durad (19)

Chapter 26 aoa
Chapter 26 aoaChapter 26 aoa
Chapter 26 aoa
 
Chapter 25 aoa
Chapter 25 aoaChapter 25 aoa
Chapter 25 aoa
 
Chapter 24 aoa
Chapter 24 aoaChapter 24 aoa
Chapter 24 aoa
 
Chapter 23 aoa
Chapter 23 aoaChapter 23 aoa
Chapter 23 aoa
 
Chapter 12 ds
Chapter 12 dsChapter 12 ds
Chapter 12 ds
 
Chapter 10 ds
Chapter 10 dsChapter 10 ds
Chapter 10 ds
 
Chapter 9 ds
Chapter 9 dsChapter 9 ds
Chapter 9 ds
 
Chapter 8 ds
Chapter 8 dsChapter 8 ds
Chapter 8 ds
 
Chapter 3 ds
Chapter 3 dsChapter 3 ds
Chapter 3 ds
 
Chapter 2 ds
Chapter 2 dsChapter 2 ds
Chapter 2 ds
 
Chapter 5 pc
Chapter 5 pcChapter 5 pc
Chapter 5 pc
 
Chapter 4 pc
Chapter 4 pcChapter 4 pc
Chapter 4 pc
 
Chapter 3 pc
Chapter 3 pcChapter 3 pc
Chapter 3 pc
 
Chapter 2 pc
Chapter 2 pcChapter 2 pc
Chapter 2 pc
 
Chapter 1 pc
Chapter 1 pcChapter 1 pc
Chapter 1 pc
 
Chapter 6 pc
Chapter 6 pcChapter 6 pc
Chapter 6 pc
 
Collective Communications in MPI
 Collective Communications in MPI Collective Communications in MPI
Collective Communications in MPI
 
Point-to-Point Communicationsin MPI
Point-to-Point Communicationsin MPIPoint-to-Point Communicationsin MPI
Point-to-Point Communicationsin MPI
 
Introduction to MPI
Introduction to MPI Introduction to MPI
Introduction to MPI
 

Recently uploaded

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 

Recently uploaded (20)

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 

Chapter 6 ds

  • 1. Chapter 6 Stacks Dr. Muhammad Hanif Durad Department of Computer and Information Sciences Pakistan Institute Engineering and Applied Sciences hanif@pieas.edu.pk Some slides have bee adapted with thanks from some other lectures available on Internet. It made my life easier, as life is always miserable at PIEAS (Sir Muhammad Yusaf Kakakhil )
  • 2. Dr. Hanif Durad 2 Lecture Outline  Introduction  Stack  Stack operations  Implementation of Stacks  Arrays  Linked lists  Applications of Stack
  • 3. Introduction  Stack  The element deleted from the set is the one most recently inserted  Last-in, First-out (LIFO) D:DSAL5165 Advanced Algorithm and Programming Languageunit09.ppt
  • 4. Introduction  Stack operations  PUSH: Insert  POP: Delete  TOP: return the key value of the most recently inserted element  STACK-EMPTY: check if the stack is empty  STACK-FULL: check if the stack is full
  • 5. An Example of Stack 2 8 1 7 2 7 2 1 7 2 1 7 2 8 1 7 2 8 1 7 2 top top top top top top Push(8) Push(2) pop(2) pop(8)pop(1) D:Data StructuresICS202Lecture10.ppt
  • 6. Implementation of Stacks  Any list implementation could be used to implement a stack  Arrays (static: the size of stack is given initially)  Linked lists (dynamic: never become full)  We will explore implementations based on array and linked list  Let’s see how to use an array to implement a stack first
  • 7. Represent Stack by Array  A stack of at most n elements can be implemented by an array S[1..n]  top[S]: a pointer to the most recently inserted element  A stack consists of elements S[1..top[S]]  S[1]: the element at the bottom of the stack  S[top[S]]: the element at the top
  • 8. Stack Operations How to implement TOP(S), STACK-FULL(S) ? O(1)
  • 9. Illustration of PUSH 15 6 2 9S top[S]=4 PUSH(S, 17) 15 6 2 9S top[S]=4 top[S]=5 top[S]  top[S] + 1 (top[S] = 5) S[top[S]]  x (S[5] = 17) 17
  • 10. Illustration of POP 15 6 2 9 17 3S top[S]=6 POP(S) 15 6 2 9 17 3S top[S]=6 top[S]=5 top[S]  top[S] - 1 (top[S] = 5) return S[top[S]+1] (return S[6]) 3
  • 11. 11  Nodes (data, pointer) connected in a chain by links  the head or the tail of the list could serve as the top of the stack Linked List Implementation D:Data StructuresHanif_SearchQueuesad5.ppt
  • 12. Applications of Stack Dr. Hanif Durad 12
  • 13. Applications of Stack  Direct applications  Parenthesis matching  Polish postfix and prefix notations  Expression evaluations  Undo sequence in a text editor  Handling function calls and return  Handling recursion  Indirect applications  Auxiliary data structure for algorithms  Component of other data structures +++ many more
  • 14. Parenthesis Matching (1/2)  To check that every right brace, bracket, and parentheses must correspond to its left counterpart  e.g. [( )] is legal, but [( ] ) is illegal Dr. Hanif Durad 14 D:Data StructuresHanif_SearchStacks stack-queue.ppt,P-18/44
  • 15. Parenthesis Matching (2/2)  Algorithm (1) Make an empty stack. (2) Read characters until end of file i. If the character is an opening symbol, push it onto the stack ii. If it is a closing symbol, then if the stack is empty, report an error iii. Otherwise, pop the stack. If the symbol popped is not the corresponding opening symbol, then report an error (3) At end of file, if the stack is not empty, report an err Dr. Hanif Durad 15
  • 16. Parenthesis Matching Example Dr. Hanif Durad 16 D:Data StructuresHanif_SearchStacks Example: On board. DS1, P-185
  • 17. 17 RPN or Postfix Notation  Most compilers convert an expression in infix notation to postfix  the operators are written after the operands  So a * b + c becomes a b * c +  Advantage:  expressions can be written without parentheses chapter07.ppt
  • 18. 18 Postfix and Prefix Examples INFIX RPN (POSTFIX) PREFIX A + B A * B + C A * (B + C) A - (B - (C - D)) A - B - C - D * A + B C + * A B C -A-B-C D ---A B C D + A B Prefix : Operators come before the operands A B + A B * C + A B C + * A B C D--- A B-C-D-
  • 19. Algorithm for Infix to Postfix 1) Examine the next element in the input. 2) If it is operand, output it. 3) If it is opening parenthesis, push it on stack. 4) If it is an operator, then i) If stack is empty, push operator on stack. ii) If the top of stack is opening parenthesis, push operator on stack iii) If it has higher priority than the top of stack, push operator on stack. iv) Else pop the operator from the stack and output it, repeat step 4 5) If it is a closing parenthesis, pop operators from stack and output them until an opening parenthesis is encountered. pop and discard the opening parenthesis. 6) If there is more input go to step 1 7) If there is no more input, pop the remaining operators to output. Lecture 10,11 Stacks.pptx
  • 20. Suppose we want to convert 2*3/(2-1)+5*3 into Postfix form, So, the Postfix Expression is 23*21-/53*+ 2 Empty 2 * * 2 3 * 23 / / 23* ( /( 23* 2 /( 23*2 - /(- 23*2 1 /(- 23*21 ) / 23*21- + + 23*21-/ 5 + 23*21-/5 3 +* 23*21-/53 Expression Stack Output * +* 23*21-/53 Empty 23*21-/53*+
  • 21. Evaluation a postfix expression • Each operator in a postfix string refers to the previous two operands in the string. • Suppose that each time we read an operand we push it into a stack. When we reach an operator, its operands will then be top two elements on the stack • We can then pop these two elements, perform the indicated operation on them, and push the result on the stack. • So that it will be available for use as an operand of the next operator.
  • 22. Evaluating Postfix Notation • Use a stack to evaluate an expression in postfix notation. • The postfix expression to be evaluated is scanned from left to right. • Variables or constants are pushed onto the stack. • When an operator is encountered, the indicated action is performed using the top elements of the stack, and the result replaces the operands on the stack.
  • 23. Evaluating a postfix expression • Initialise an empty stack • While token remain in the input stream –Read next token –If token is a number, push it into the stack –Else, if token is an operator, pop top two tokens off the stack,apply the operator, and push the answer back into the stack • Pop the answer off the stack.
  • 26. Function calls  Programming languages use stacks to keep track of function calls  When a function call occurs  Push CPU registers and program counter on to stack (“activation record” or “stack frame”)  Upon return, restore registers and program counter from top stack frame and pop Dr. Hanif Durad 26 D:Data StructuresCPT S 223adt.ppt, P-47/52