Stacks, Queues & Recursion

Slides:



Advertisements
Similar presentations
Data Structures Through C
Advertisements

§3 The Stack ADT 1. ADT A stack is a Last-In-First-Out (LIFO) list, that is, an ordered list in which insertions and deletions are.
CS Data Structures ( 資料結構 ) Chapter 3: Stacks and Queues Spring 2012.
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Stacks Chapter 11.
Arithmetic Expressions Infix form –operand operator operand 2+3 or a+b –Need precedence rules –May use parentheses 4*(3+5) or a*(b+c)
Stacks Example: Stack of plates in cafeteria.
C o n f i d e n t i a l Developed By Nitendra NextHome Subject Name: Data Structure Using C Title : Overview of Stack.
E.G.M. Petrakislists, stacks, queues1 Stacks Stack: restricted variant of list –Elements may by inserted or deleted from only one end  LIFO lists –Top:
Lecture - 9 On Queues. Prepared by, Jesmin Akhter, Lecturer, IIT,JU QUEUES A Queue is a linear list of elements in which deletions can take place only.
 Balancing Symbols 3. Applications
E.G.M. Petrakisstacks, queues1 Stacks  Stack: restricted variant of list  elements may by inserted or deleted from only one end : LIFO lists  top: the.
Infix, Postfix, Prefix.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Stack  A stack is a linear data structure or abstract data type for collection of items, with the restriction that items can be added one at a time and.
Objectives of these slides:
Ceng-112 Data Structures ITurgut Kalfaoglu 1 Chapter 3 Stacks.
Data Structures Lecture : Stacks (Infix, Postfix and Prefix Expressions) Azhar Maqsood NUST Institute of Information Technology (NIIT)
Stack Applications.
CSC 205 Programming II Postfix Expressions. Recap: Stack Stack features Orderly linear structure Access from one side only – top item Stack operations.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Chapter 4 Stacks Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving. Its called.
Computer Science Department Data Structure & Algorithms Problem Solving with Stack.
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
CHAPTER 61 STACK, QUEUES, RECURSION. Introduction when one wants to restrict insertion and deletion so that they can take place only at the beginning.
Queue 1 Operations on Queues A Dequeue Operation An Enqueue Operation Array Implementation Link list Implementation Examples.
Stack Any Other Data Structure Array Linked List
CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 19: Stacks and Queues (part 2)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
Queue 09/10/081. Queue (Linear Queue) It is a linear data structure consisting of list of items. In queue, data elements are added at one end, called.
CHP-3 STACKS.
Part 2. Deletion from a linked list Let LIST be a linked list with a node N between nodes A and B. suppose node N is to be deleted from the linked list.
Prof. I. J. Chung Data Structure #5 Professor I. J. Chung.
CC 215 DATA STRUCTURES MORE ABOUT STACK APPLICATIONS Dr. Manal Helal - Fall 2014 Lecture 6 AASTMT Engineering and Technology College 1.
Stacks Chapter 3 Objectives Upon completion you will be able to
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
Lecture - 6(Stacks) On Data structures. Prepared by, Jesmin Akhter, Lecturer, IIT,JU Lecture Outline What is a Stack? Array implementation of stacks Operations.
Data Structures & Algorithm CS-102
Part 2. Deletion from a linked list Let LIST be a linked list with a node N between nodes A and B. suppose node N is to be deleted from the linked list.
 In general, Queue is line of person waiting for their turn at some service counter like ticket window at cinema hall, at bus stand or at railway station.
© Oxford University Press All rights reserved. Data Structures Using C, 2e Reema Thareja.
© Oxford University Press All rights reserved. Data Structures Using C, 2e Reema Thareja.
Review Use of Stack Introduction Stack in our life Stack Operations
STACKS & QUEUES for CLASS XII ( C++).
Data Structures Using C, 2e
Queues.
DATA STRUCTURES AND OBJECT ORIENTED PROGRAMMING IN C++
Objectives In this lesson, you will learn to: Define stacks
QUEUE.
STACKS.
Stacks Stack: restricted variant of list
Stacks Chapter 4.
Stack application: postponing data usage
Algorithms and Data Structures
PART II STACK APPLICATIONS
INSERTION INTO A LINEAR ARRAY Set J = N Repeat step 3 and 4 while J>= K Set LA[ J+1] = LA [ J ] Set J = J-1 Set LA [K] = ITEM Set N = N+1 Exit.
Stacks Chapter 5 Adapted from Pearson Education, Inc.
More About Stacks: Stack Applications
STACK, QUEUES, RECURSION
UNIT-I Topics to be covere d 1.Introduction to data structures.
Stacks and Queues 1.
Queue Applications Lecture 31 Mon, Apr 9, 2007.
(Part 2) Infix, Prefix & Postfix
Stack.
Queue Applications Lecture 31 Tue, Apr 11, 2006.
More About Stacks: Stack Applications
Presented by : Aman Gupta PGT CS KV No.1, Narimedu, Madurai
Stacks A stack is an ordered set of elements, for which only the last element placed into the stack is accessible. The stack data type is also known as.
Presentation transcript:

Stacks, Queues & Recursion Stacks: LIFO Last In First Out Queues: FIFO First In First Out

QUEUES FIFO Queue is a linear structure in which Deletions can take place at one end only, called the Front and Insertions can take place only at other end, called the Rear. Three everyday examples of such a structure Waiting Automobiles for Fuel People Waiting in Line at Bank Programs with the same Priority Another structure called priority queue AAA Front DDD Rear AAA BBB CCC DDD

Representation of Queues FRONT: Containing the Location of the Front Element REAR: Containing the Location of the Rear Element FRONT = NULL will indicate the Queue is Empty Deletion: FRONT := FRONT + 1 Insertion: REAR := REAR + 1 After N Insertions, the Rear Element of the Queue will Occupy QUEUE [N]

Representation of Queues Cont… FRONT-1 AAA BBB CCC DDD ……. ……. …… REAR -4 1 2 3 4 5 6 N FRONT-2 BBB CCC DDD ……. ……. …… REAR -4 1 2 3 4 5 6 N FRONT-2 BBB CCC DDD EEE FFF …… REAR -6 1 2 3 4 5 6 N FRONT-3 CCC DDD EEE FFF …… REAR -6 1 2 3 4 5 6 N

Circular Queues QUEUE [1] comes after QUEUE [N] in the array Instead of increasing REAR to N+1 we reset REAR=1 QUEUE [REAR]:= ITEM Instead of Increasing FRONT to N+1 we reset FRONT= 1 Queue contains only one Element FRONT = REAR  NULL For No Element FRONT := NULL REAR := NULL

(a) Initially Empty FRONT-0 REAR -0 1 2 3 4 5 (b) A,B,C FRONT-1 A B C Inserted REAR -3 1 2 3 4 5 (c) A Deleted FRONT-2 B C REAR - 3 1 2 3 4 5 (d) D and then FRONT-2 B C D E E Inserted REAR - 5 1 2 3 4 5 (e) B and C FRONT-4 D E Deleted REAR - 5 1 2 3 4 5

(f) F Inserted FRONT-4 F D E REAR -1 1 2 3 4 5 (g) D Deleted FRONT-5 F E REAR -1 1 2 3 4 5 (h) G and then FRONT-5 F G H E H Inserted REAR -3 1 2 3 4 5 (i) E Deleted FRONT-1 F G H REAR -3 1 2 3 4 5 (j) F Deleted FRONT-2 G H REAR -3 1 2 3 4 5

(k) K Inserted FRONT-2 G H K REAR -4 1 2 3 4 5 (l) G and H FRONT-4 K Deleted REAR -4 1 2 3 4 5 (m) K Deleted FRONT-0 Queue Empty REAR -0 1 2 3 4 5

QINSERT (QUEUE, N, FRONT, REAR, ITEM) This procedure inserts an element ITEM into a queue. [Queue already filled?] If FRONT =1 and REAR = N, or if FRONT=REAR+1 Then write: OVERFLOW and return [Find new value of REAR] If FRONT:=NULL [QUEUE Initially empty] Then : Set FRONT:=1 and REAR:=1 Else If REAR =N then Set REAR:=1 Else: Set REAR:=REAR+1 [End of If structure] Set QUEUE[REAR]:=ITEM [ This inserts new element] Return

QDELETE (QUEUE, N, FRONT, REAR, ITEM) This procedure deletes an element from a queue and assigns it to the variable item. [QUEUE already empty?] If FRONT:=NULL, then write: UNDERFLOW and Return Set ITEM:=QUEUE[FRONT] [Find new value of FRONT] If FRONT=REAR, then [Queue has only one element to start] Set FRONT:=NULL and REAR:=NULL Else if FRONT:=N then Set FRONT:=1 Else Set FRONT:=FRONT+1 [End of If Structure] Return

STACKS LIFO A stack is a linear structure in which items are added or removed only at one end. Three everyday examples of such a structure Stack of dishes Stack of pennies Stack of folded towels In particular the last item to be added to stack is the first item to be removed STACKS are also called “PILES” AND “PUSH- DOWN”

Operations On Stack PUSH: is the term to insert an element into a stack POP: is the term to delete an element from a stack Example: Suppose the following 6 elements are pushed in order onto an empty stack AAA, BBB, CCC, DDD, EEE, FFF This means: EEE cannot be deleted before FFF is deleted, DDD cannot be deleted before EEE and FFF is deleted and so on. AAA BBB CCC FFF DDD EEE EEE DDD FFF TOP CCC BBB AAA

POSTPONED DECISIONS Stacks are frequently used to indicate the order of the processing of data when certain steps of the processing must be postponed until other conditions are fulfilled. C B B B A A A

Operation Of Stack CreateStack (Size) DestroyStack(Stack) Function: Initialize Stack to an Empty State Input: None Precondition: None Output: Stack Post condition: Stack is Empty DestroyStack(Stack) Function: Remove all the Elements from Stack Input: Stack Precondition: Stack has been created

Operation Of Stack Cont…. EmptyStack (Stack) Function: Test whether stack is Empty Input: Stack Precondition: Stack has been created Output: EmptyStack (Boolean) FullStack(Stack) Function: Test whether stack is Full Precondition: Stack has been created Output: FullStack (Boolean)

Operation Of Stack Cont…. Push (Stack, NewValue) Function: Add new value in a Stack Input: Stack, New Value Precondition: Stack has been created and not Full Output: Stack Post condition: New Value will be added in the Stack New Top will be assigned Pop(Stack, PoppedValue) Function: Remove the top value from the Stack Input: Stack Precondition: Stack has been created and not Empty Output: Stack, Popped Value Post condition: New Top will be assigned

PUSH (STACK, TOP, MAXSTR, ITEM) This procedure pushes an ITEM onto a stack If TOP = MAXSTR, then Print: OVERFLOW, and Return. Set TOP := TOP + 1 [Increases TOP by 1] Set STACK [TOP] := ITEM. [Insert ITEM in TOP position] Return POP (STACK, TOP, ITEM) This procedure deletes the top element of STACK and assign it to the variable ITEM If TOP = 0, then Print: UNDERFLOW, and Return. Set ITEM := STACK[TOP] Set TOP := TOP - 1 [Decreases TOP by 1]

Arithmetic Expressions Precedence Level Highest Exponentiation ( ) Next Highest Multiplication (*) and Division ( / ) Lowest: Addition (+) and subtraction (-) Infix Notation A + B C – D (G / H) + A Polish Notation (Prefix Notation) + AB - CD (/ GH) + A = + / GHA Reverse Polish Notation (Postfix or Suffix Notation) AB + CD - GHA / +

Evaluation of Expression The Computer Usually Evaluates an Arithmetic expression written in infix notation into steps First converts the expression to postfix notation Evaluates the postfix expression Stack is the Main Tool that is Used to Accomplish given Task. INFIX PREFIX ( A + B ) * C [ + A B ] * C = * + A B A + ( B * C ) A + [ * B C ] = + A * B C ( A + B ) / ( C – D ) [+ AB] / [- CD] = / + AB-CD

This Algorithm Finds the VALUE of an Arithmetic Expression P Written in Postfix Notation. Add a right parenthesis “)” at the end of P. Scan P from left to right and repeat step 3 and 4 for each element of P until “)”is encountered. If an operand is encountered, put it in STACK. If an operator X is encountered then: Remove the two top elements of STACK Evaluate B X A Place the result of (b) back on STACK. [End of IF Structure] [End of STEP2 loop] Set VALUE equal to the top element on STACK. Exit

Stack Postfix Operation Q: 5 * ( 6 + 2 ) – 12 / 4 P : 5 , 6 , 2 , + , * , 12 , 4 , / , - , ) Symbol Scanned STACK 5 5 6 5,6 2 5,6,2 + 5,8 * 40 12 40,12 4 40, 12, 4 / 40, 3 - 37 )

Transforming Infix to Postfix The following Algorithm Transforms the Infix Expression Q into its Equivalent Postfix Expression P The Algorithm uses a STACK to Temporarily Hold Operators and Left Parentheses. The Postfix Expression P will be Constructed from Left to Right using the Operands and Left Parentheses. The Postfix Expression P will be Constructed from Left to Right using the Operands from Q and the Operators which are Removed from STACK We begin by Pushing a Left Parenthesis onto STACK and Adding Right Parentheses at the End of Q The Algorithm is Completed when STACK is Empty.

Algorithm: POLISH (Q, P) PUSH “(” onto STACK, and add “)” to the end of Q Scan Q from left to right and repeat step 3 to step 6 for each element of Q until the STACK is empty. If an operands is encountered, add it to P If a left parenthesis is encountered, push it onto STACK If an operator X is encountered then: Repeatedly POP from STACK and add to P each operator (on the top of STACK) which has the same precedence as or higher precedence than X Add X to STACK [END of IF Structure] If a right parenthesis is encountered then: Repeatedly POP from STACK and add to P each operator (on the top of STACK) until a left parenthesis is encountered. Remove the left parenthesis [END of STEP 2 loop] EXIT

Q: A + ( B * C - ( D / E F ) * G ) * H ) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Symbol STACK Expression P A ( A + ( + A ( ( + ( A B ( + ( A B * ( + ( * A B C ( + ( * A B C - ( + ( - A B C * ( ( + ( - ( A B C * D ( + ( - ( A B C * D / ( + ( - ( / A B C * D E ( + ( - ( / A B C * D E

Q: A + ( B * C - ( D / E F ) * G ) * H ) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Symbol STACK Expression P ( + ( - ( / A B C * D E F ( + ( - ( / A B C * D E F ) ( + ( - A B C * D E F / * ( + ( - * A B C * D E F / G ( + ( - * A B C * D E F / G ) ( + A B C * D E F / G * - * ( + * A B C * D E F / G * - H ( + * A B C * D E F / G * - H ) A B C * D E F / G * - H * + P: A B C * D E F / G * - H * +

RECURSION Recursive Procedure and Function Recursion occurs when a Procedure call itself A Procedure call some other procedure that calls the calling Procedure again It is called a Recursive Procedure Procedure must contain a base criteria Procedure must be closer to the base criteria after each call It is called a Well Defined procedure

Factorial Function Product of Positive Integer from 1 to n Denoted by n! => n! = 1.2.3….(n-2).(n-1).n 0! = 1 , 5! = 1.2.3.4.5 = 120, 6! = 5! . 6 = 720 n! = n . ( n – 1 )! Definition If n = 0 then n! = 1 If n > 0, then n! = n. (n-1) !

Example: Postpone Decision 4! = 4 . 3! 3! = 3 . 2! 2! = 2. 1! 1! = 1. 0! 0! = 1 1! = 1.1 = 1 2! = 2.1 = 2 3! = 3.2 = 6 4! = 4.6 = 24

Reading Assignments: Level Number and Depth of Recursion FACTORIAL (FACT,N) 1 If N = 0 then Set FACT = 1 and Return 2 Set FACT := 1 [Initialize FACT for loop] 3 Repeat for K = 1 to N Set FACT := K * FACT [End of Loop] 4 Return FACTORIAL (FACT, N) 1 If N = 0 then Set FACT = 1 and Return 2 Call FACTORIAL (FACT, N – 1) 3 Set FACT := N * FACT Reading Assignments: Level Number and Depth of Recursion

DEQUES Input Restricted Deque Output Restricted Deque Insertion at Only One End but Deletion from Both Ends Output Restricted Deque Deletion from One End but Insertion at Both Ends

PRIORITY QUEUES Each Element has its own priority Higher Priority Elements will Processed before Lower Priority Elements Same Priority Elements will Processed According to their Order Can be Implemented by a One-Way List or Multiple Queues Reading Assignment Array Representation of Priority Queues

One-Way List Implementation Each Node Contain Three Fields INFO Field: Contains the Data PRN Field : Contains the Priority Number LINK Field : Link to the Next Node Start 1 2 2 AAA BBB CCC 3 4 5 DDD EEE FFF 3 GGG

Quick Sort An Stacks Application Quick Sort works on Divide and Conquer Rule Quick Sort Strategy is to Divide a List or Set into Two Sub-Lists or Sub-Sets. Pick an Element, Called a Pivot, from the List. Reorder the List so that all Elements which are Less than the Pivot come Before the Pivot and so that All Elements Greater than the Pivot come After it. After this Partitioning, the Pivot is in its Final Position. This is called the Partition operation. Recursively Sort the Sub-List of Lesser Elements and the Sub-List of Greater Elements.

Starting from the Right to Find the Number < 44 44 33 11 55 77 90 40 60 99 22 88 66 Starting from the Right to Find the Number < 44 22 33 11 55 77 90 40 60 99 44 88 66 From the Left to Find the Number > 44 22 33 11 44 77 90 40 60 99 55 88 66 22 33 11 40 77 90 44 60 99 55 88 66 22 33 11 40 44 90 77 60 99 55 88 66 Now 44 is on its Correct Position We can Process only One Sub-List at a Time Two Stacks Lower and Upper will be used

Lower Empty Upper Empty Lower 1,6 Upper 4,12 Lower 1,6 Upper 4,10 Boundary Values : Address of the First and Last values of Sub-List Lower 1 Upper 12 Lower Empty Upper Empty Lower 1,6 Upper 4,12 Lower 1,6 Upper 4,10 A[6] A[7] A[8] A[9] A[10] A[11] A[12] 90 77 60 99 55 88 66 66 77 60 99 55 88 90 66 77 60 90 55 88 99 66 77 60 88 55 90 99 First Sub-List Second Sub-List

QUICK ( A, N, BEG, END, LOC ) A : Name of Array N : Number of Elements BEG : Beginning Boundary Value END : Ending Boundary Value LOC : Position of the First Element Local Variables : LEFT RIGHT

1. [Initialize] Set LEFT := BEG, RIGHT := END and LOC := BEG 2 1. [Initialize] Set LEFT := BEG, RIGHT := END and LOC := BEG 2. [Scan from Right to Left] a) Repeat while A[LOC] <= A[RIGHT] RIGHT := RIGHT – 1 [End of Loop] b) If LOC = RIGHT, then : Return c) If [LOC] > A [RIGHT] ,then: 1) [Interchange A [LOC] and A[RIGHT] ] TEMP := A[LOC], A[LOC] = A[RIGHT], A[RIGHT]=TEMP 2) Set LOC := RIGHT 3) Go to Step 3 [End of If Structure]

3. [Scan from Left to Right] a) Repeat while A[LEFT] <= A[LOC] LEFT := LEFT + 1 [End of Loop] b) If LOC = LEFT, then : Return c) If [LEFT] > A [LOC] ,then: 1) [Interchange A [LEFT] and A[LOC] ] TEMP := A[LOC], A[LOC] = A[LEFT], A[LEFT]=TEMP 2) Set LOC := LEFT 3) Go to Step 2 [End of If Structure]

[Initialize] TOP := 0 [PUSH Boundary values of A onto Stacks when 2 or More Elements] If N > 1, then TOP:=TOP+1, LOWER[1]:=1, UPPER[1]:=N Repeat Steps 4 to 7 while TOP != 0 [Pop Sub-List from Stacks] Set BEG := LOWER[TOP] , END := UPPER[TOP] TOP := TOP -1 Call QUICK (A, N, BEG, END, LOC) [Push Left Sub-List onto Stacks when 2 or More Elements] If BEG < LOC - 1 then TOP := TOP + 1, LOWER[TOP] := BEG, UPPER[TOP] := LOC – 1 [End of If Structure] [Push Right Sub-List onto Stacks when 2 or More Elements] If LOC + 1 < END then TOP := TOP + 1, LOWER[TOP] := LOC + 1, UPPER[TOP] := END [End of If Structure] [End of Step 3 Loop] [Exit] (Quick Sort)

Reading Assignments Minimizing Overflow page: 168 Recursion 6.6 Tower of Hanoi 6.7 Implementation of Recursion by Stack 6.8 Double Ended Queue DEQUES 6.10 Priority Queues 6.11