C Programming: Program Design Including Data Structures, Fifth Edition - PowerPoint PPT Presentation

1 / 115
About This Presentation
Title:

C Programming: Program Design Including Data Structures, Fifth Edition

Description:

Program Design Including Data Structures, Fifth Edition Chapter 18: Stacks and Queues front and back Operations C++ Programming: Program Design Including Data ... – PowerPoint PPT presentation

Number of Views:212
Avg rating:3.0/5.0
Slides: 116
Provided by: ocCourseC5
Category:

less

Transcript and Presenter's Notes

Title: C Programming: Program Design Including Data Structures, Fifth Edition


1
C ProgrammingProgram Design IncludingData
Structures, Fifth Edition
  • Chapter 18 Stacks and Queues

2
Objectives
  • In this chapter, you will
  • Learn about stacks
  • Examine various stack operations
  • Learn how to implement a stack as an array
  • Learn how to implement a stack as a linked list
  • Discover stack applications
  • Learn how to use a stack to remove recursion

3
Objectives (cont'd.)
  • Learn about queues
  • Examine various queue operations
  • Learn how to implement a queue as an array
  • Learn how to implement a queue as a linked list
  • Discover queue applications

4
Stacks
  • Stack list of homogenous elements
  • Addition and deletion occur only at one end,
    called the top of the stack
  • Example in a cafeteria, the second tray can be
    removed only if first tray has been removed
  • Last in first out (LIFO) data structure
  • Operations
  • Push to add an element onto the stack
  • Pop to remove an element from the stack

5
Stacks (contd.)
6
Stacks (contd.)
7
Stack Operations
  • In the abstract class stackADT
  • initializeStack
  • isEmptyStack
  • isFullStack
  • push
  • top
  • pop

8
Implementation of Stacks as Arrays
  • First element can go in first array position, the
    second in the second position, etc.
  • The top of the stack is the index of the last
    element added to the stack
  • Stack elements are stored in an array
  • Stack element is accessed only through top
  • To keep track of the top position, use a variable
    called stackTop

9
Implementation of Stacks as Arrays (cont'd.)
  • Because stack is homogeneous
  • You can use an array to implement a stack
  • Can dynamically allocate array
  • Enables user to specify size of the array
  • The class stackType implements the functions of
    the abstract class stackADT

10
Implementation of Stacks as Arrays (cont'd.)
11
Implementation of Stacks as Arrays (cont'd.)
  • C arrays begin with the index 0
  • Must distinguish between
  • The value of stackTop
  • The array position indicated by stackTop
  • If stackTop is 0, the stack is empty
  • If stackTop is nonzero, the stack is not empty
  • The top element is given by stackTop - 1

12
Implementation of Stacks as Arrays (cont'd.)
13
Initialize Stack
14
Empty Stack
  • If stackTop is 0, the stack is empty

15
Full Stack
  • The stack is full if stackTop is equal to
    maxStackSize

16
Push
  • Store the newItem in the array component
    indicated by stackTop
  • Increment stackTop
  • Must avoid an overflow

17
Push (cont'd.)
18
Return the Top Element
19
Pop
  • Simply decrement stackTop by 1
  • Must check for underflow condition

20
Pop (contd.)
21
Pop (contd.)
22
Copy Stack
23
Constructor and Destructor
24
Constructor and Destructor (cont'd.)
25
Copy Constructor
26
Overloading the Assignment Operator ()
27
Stack Header File
  • Place definitions of class and functions (stack
    operations) together in a file

28
Programming Example Highest GPA
  • Input program reads an input file with each
    students GPA and name
  • 3.5 Bill
  • 3.6 John
  • 2.7 Lisa
  • 3.9 Kathy
  • 3.4 Jason
  • 3.9 David
  • 3.4 Jack
  • Output the highest GPA and all the names
    associated with the highest GPA

29
Programming Example Problem Analysis and
Algorithm Design
  • Read the first GPA and name of the student
  • This is the highest GPA so far
  • Read the second GPA and student name
  • Compare this GPA with highest GPA so far
  • New GPA is greater than highest GPA so far
  • Update highest GPA, initialize stack, add to
    stack
  • New GPA is equal to the highest GPA so far
  • Add name to stack
  • New GPA is smaller than the highest GPA
  • Discard

30
Programming Example Problem Analysis and
Algorithm Design (contd.)
31
Programming Example Problem Analysis and
Algorithm Design (contd.)
32
Linked Implementation of Stacks
  • Array only allows fixed number of elements
  • If number of elements to be pushed exceeds array
    size
  • Program may terminate
  • Linked lists can dynamically organize data
  • In a linked representation, stackTop is pointer
    to top element in stack

33
Linked Implementation of Stacks (contd.)
34
Default Constructor
  • Initializes the stack to an empty state when a
    stack object is declared
  • Sets stackTop to NULL

35
Empty Stack and Full Stack
  • In the linked implementation of stacks, the
    function isFullStack does not apply
  • Logically, the stack is never full

36
Initialize Stack
37
Push
  • The newElement is added at the beginning of the
    linked list pointed to by stackTop

38
Push (cont'd.)
39
Push (cont'd.)
  • We do not need to check whether the stack is full
    before we push an element onto the stack

40
Return the Top Element
41
Pop
  • Node pointed to by stackTop is removed

42
Pop (cont'd.)
43
Pop (cont'd.)
44
Copy Stack
45
Copy Stack (cont'd.)
  • Notice that this function is similar to the
    definition of copyList for linked lists

46
Constructors and Destructors
47
Overloading the Assignment Operator ()
48
Stack as Derived from the class
unorderedLinkedList
  • Our implementation of push is similar to
    insertFirst (discussed for general lists)
  • Other functions are similar too
  • initializeStack and initializeList
  • isEmptyList and isEmptyStack
  • linkedStackType can be derived from
    linkedListType
  • class linkedListType is abstract
  • Must implement pop as described earlier

49
Derived Stack (contd.)
  • unorderedLinkedListType is derived from
    linkedListType
  • Provides the definitions of the abstract
    functions of the class linkedListType
  • We can derive the linkedStackType from
    unorderedLinkedListType

50
Application of Stacks Postfix Expressions
Calculator
  • Infix notation usual notation for writing
    arithmetic expressions
  • The operator is written between the operands
  • Example a b
  • The operators have precedence
  • Parentheses can be used to override precedence

51
Application of Stacks Postfix Expressions
Calculator (cont'd.)
  • Prefix (Polish) notation the operators are
    written before the operands
  • Introduced by the Polish mathematician Jan
    Lukasiewicz
  • Early 1920s
  • The parentheses can be omitted
  • Example a b

52
Application of Stacks Postfix Expressions
Calculator (cont'd.)
  • Reverse Polish notation the operators follow the
    operands (postfix operators)
  • Proposed by the Australian philosopher and early
    computer scientist Charles L. Hamblin
  • Late 1950's
  • Advantage the operators appear in the order
    required for computation
  • Example a b c
  • In a postfix expression a b c

53
Application of Stacks Postfix Expressions
Calculator (cont'd.)
54
Application of Stacks Postfix Expressions
Calculator (cont'd.)
  • Postfix notation has important applications in
    computer science
  • Many compilers first translate arithmetic
    expressions into postfix notation and then
    translate this expression into machine code
  • Evaluation algorithm
  • Scan expression from left to right
  • When an operator is found, back up to get the
    operands, perform the operation, and continue

55
Application of Stacks Postfix Expressions
Calculator (cont'd.)
  • Example 6 3 2

56
Application of Stacks Postfix Expressions
Calculator (cont'd.)
  • Symbols can be numbers or anything else
  • , -, , and / are operators
  • Pop stack twice and evaluate expression
  • If stack has less than two elements ? error
  • If symbol is , the expression ends
  • Pop and print answer from stack
  • If stack has more than one element ? error
  • If symbol is anything else
  • Expression contains an illegal operator

57
Application of Stacks Postfix Expressions
Calculator (cont'd.)
  • Examples
  • 7 6 3 6 -
  • is an illegal operator
  • 14 2 3
  • Does not have enough operands for
  • 14 2 3
  • Error stack will have two elements when we
    encounter equal () sign

58
Application of Stacks Postfix Expressions
Calculator (cont'd.)
  • We assume that the postfix expressions are in the
    following form
  • 6 3 2
  • If symbol scanned is , next input is a number
  • If the symbol scanned is not , then it is
  • An operator (may be illegal) or
  • An equal sign (end of expression)
  • We assume expressions contain only , -, , and /
    operators

59
Main Algorithm
  • Pseudocode
  • We will write four functions
  • evaluateExpression, evaluateOpr, discardExp, and
    printResult

60
Function evaluateExpression
61
Function evaluateOpr
62
Function evaluateOpr (contd.)
63
Function discardExp
  • This function is called whenever an error is
    discovered in the expression

64
Function printResult
  • If the postfix expression contains no errors, the
    function printResult prints the result
  • Otherwise, it outputs an appropriate message
  • The result of the expression is in the stack and
    the output is sent to a file

65
Function printResult (contd.)
66
Removing Recursion Nonrecursive Algorithm to
Print a Linked List Backward
  • To print the list backward, first we need to get
    to the last node of the list
  • Problem how do we get back to previous node?
  • Links go in only one direction
  • Solution save a pointer to each of the nodes
    with info 5, 10, and 15
  • Use a stack (LIFO)

67
Removing Recursion Nonrecursive Algorithm to
Print a Linked List Backward (contd.)
68
Removing Recursion Nonrecursive Algorithm to
Print a Linked List Backward (contd.)
  • Let us now execute the following statements
  • Output
  • 20 15 10 5

69
Queues
  • Queue list of homogeneous elements
  • Elements are
  • Added at one end (the back or rear)
  • Deleted from the other end (the front)
  • First In First Out (FIFO) data structure
  • Middle elements are inaccessible
  • Example
  • Waiting line in a bank

70
Queue Operations
  • Some of the queue operations are
  • initializeQueue
  • isEmptyQueue
  • isFullQueue
  • front
  • back
  • addQueue
  • deleteQueue
  • Abstract class queueADT defines these operations

71
Implementation of Queues as Arrays
  • You need at least four (member) variables
  • An array to store the queue elements
  • queueFront and queueRear
  • To keep track of first and last elements
  • maxQueueSize
  • To specify the maximum size of the queue

72
Implementation of Queues as Arrays (cont'd.)
  • To add an element to the queue
  • Advance queueRear to next array position
  • Add element to position pointed by queueRear
  • Example array size is 100 originally empty

73
Implementation of Queues as Arrays (cont'd.)
  • To delete an element from the queue
  • Retrieve element pointed to by queueFront
  • Advance queueFront to next queue element

74
Implementation of Queues as Arrays (cont'd.)
  • Will this queue design work?
  • Suppose A stands for adding an element to the
    queue
  • And D stands for deleting an element from the
    queue
  • Consider the following sequence of operations
  • AAADADADADADADADA...

75
Implementation of Queues as Arrays (cont'd.)
  • The sequence AAADADADADADADADA... would
    eventually set queueRear to point to the last
    array position
  • Giving the impression that the queue is full

76
Implementation of Queues as Arrays (cont'd.)
  • Solution 1
  • When the queue overflows to the rear (i.e.,
    queueRear points to the last array position)
  • Check value of queueFront
  • If value of queueFront indicates that there is
    room in the front of the array, slide all of the
    queue elements toward the first array position
  • Problem too slow for large queues
  • Solution 2 assume that the array is circular

77
Implementation of Queues as Arrays (cont'd.)
  • To advance the index in a (logically) circular
    array

78
Implementation of Queues as Arrays (cont'd.)
79
Implementation of Queues as Arrays (cont'd.)
  • Case 1

80
Implementation of Queues as Arrays (cont'd.)
  • Case 2

81
Implementation of Queues as Arrays (cont'd.)
  • Problem
  • Figures 19-32b and 19-33b have identical values
    for queueFront and queueRear
  • However, the former represents an empty queue,
    whereas the latter shows a full queue
  • Solution?

82
Implementation of Queues as Arrays (cont'd.)
  • Solution 1 keep a count
  • Incremented when a new element is added to the
    queue
  • Decremented when an element is removed
  • Initially, set to 0
  • Very useful if user (of queue) frequently needs
    to know the number of elements in the queue
  • We will implement this solution

83
Implementation of Queues as Arrays (cont'd.)
  • Solution 2 let queueFront indicate index of the
    array position preceding the first element
  • queueRear still indicates index of last one
  • Queue empty if
  • queueFront queueRear
  • Slot indicated by queueFront is reserved
  • Queue can hold 99 (not 100) elements
  • Queue full if the next available space is the
    reserved slot indicated by queueFront

84
Implementation of Queues as Arrays (cont'd.)
85
Empty Queue and Full Queue
86
Initialize Queue
87
Front
  • Returns the first element of the queue

88
Back
  • Returns the last element of the queue

89
addQueue
90
deleteQueue
91
Constructors and Destructors
92
Constructors and Destructors (cont'd.)
  • The array to store the queue elements is created
    dynamically
  • When the queue object goes out of scope, the
    destructor simply deallocates the memory occupied
    by the array

93
Linked Implementation of Queues
  • Array size is fixed only a finite number of
    queue elements can be stored in it
  • The array implementation of the queue requires
    array to be treated in a special way
  • Together with queueFront and queueRear
  • The linked implementation of a queue simplifies
    many of the special cases of the array
    implementation
  • In addition, the queue is never full

94
Linked Implementation of Queues (cont'd.)
  • Elements are added at one end and removed from
    the other
  • We need to know the front of the queue and the
    rear of the queue
  • Two pointers queueFront and queueRear

95
Empty and Full Queue
  • The queue is empty if queueFront is NULL
  • The queue is never full

96
Initialize Queue
  • Initializes queue to an empty state
  • Must remove all the elements, if any

97
addQueue
98
front and back Operations
99
deleteQueue
100
Default Constructor
101
Queue Derived from the class unorderedLinkedListTy
pe
  • The linked implementation of a queue is similar
    to the implementation of a linked list created in
    a forward manner
  • addQueue is similar to insertFirst
  • initializeQueue is like initializeList
  • isEmptyQueue is similar to isEmptyList
  • deleteQueue can be implemented as before
  • queueFront is the same as first
  • queueRear is the same as last

102
Queue Derived from the class unordered
LinkedListType (cont'd.)
  • We can derive the class to implement the queue
    from linkedListType
  • Abstract class does not implement all the
    operations
  • However, unorderedLinkedListType is derived from
    linkedListType
  • Provides the definitions of the abstract
    functions of the linkedListType
  • Therefore, we can derive linkedQueueType from
    unorderedLinkedListType

103
Application of Queues Simulation
  • Simulation a technique in which one system
    models the behavior of another system
  • Computer simulations using queues as the data
    structure are called queuing systems

104
Designing a Queuing System
  • Server the object that provides the service
  • Customer the object receiving the service
  • Transaction time service time, or the time it
    takes to serve a customer
  • Model system that consists of a list of servers
    and a waiting queue holding the customers to be
    served
  • Customer at front of queue waits for the next
    available server

105
Designing a Queuing System (cont'd.)
  • We need to know
  • Number of servers
  • Expected arrival time of a customer
  • Time between the arrivals of customers
  • Number of events affecting the system
  • Performance of system depends on
  • How many servers are available
  • How long it takes to serve a customer
  • How often a customer arrives

106
Designing a Queuing System (cont'd.)
  • If it takes too long to serve a customer and
    customers arrive frequently, then more servers
    are needed
  • System can be modeled as a time-driven simulation
  • Time-driven simulation the clock is a counter
  • The passage of, say, one minute can be
    implemented by incrementing the counter by 1
  • Simulation is run for a fixed amount of time

107
Customer
108
Server
109
Server List
  • A server list is a set of servers
  • At a given time, a server is either free or busy

110
Waiting Customers Queue
  • When a customer arrives, he/she goes to the end
    of the queue
  • When a server becomes available, the customer at
    front of queue leaves to conduct the transaction
  • After each time unit, the waiting time of each
    customer in the queue is incremented by 1
  • We can use queueType but must add the operation
    of incrementing the waiting time

111
Waiting Customers Queue (cont'd.)
112
Main Program
  • Algorithm
  • Declare and initialize the variables
  • Main loop (see next slide)
  • Print results

113
Main Program (cont'd.)
114
Summary
  • Stack items are added/deleted from one end
  • Last In First Out (LIFO) data structure
  • Operations push, pop, initialize, destroy, check
    for empty/full stack
  • Can be implemented as array or linked list
  • Middle elements should not be accessed
  • Postfix notation operators are written after the
    operands (no parentheses needed)

115
Summary (cont'd.)
  • Queue items are added at one end and removed
    from the other end
  • First In First Out (FIFO) data structure
  • Operations add, remove, initialize, destroy,
    check if queue is empty/full
  • Can be implemented as array or linked list
  • Middle elements should not be accessed
  • Restricted versions of arrays and linked lists
Write a Comment
User Comments (0)
About PowerShow.com