0% found this document useful (0 votes)
13 views

6-Stack and Queue

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

6-Stack and Queue

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

DATA STRUCTURES AND ALGORITHMS

Chapter 6: Stack and Queue

1
Main contents

• Stacks

• Evaluation of Expression

• Queues

• Circular Queue

• Priority Queues

2
Introduction

• Abstract Data Types (ADTs) allow us to defer the


implementation details of data structures and focus on
operations
• The operations themselves often determine which
structure is most appropriate in a given situation
• In this chapter we’ll consider two such structures, stacks
and queues, where we’ll focus on operations first
• Once we have determined what operations are needed
and how they behave, we’ll consider implementations

3
Stacks
• A stack is a restricted access linear data structure
• It can only be accessed at one of its ends for adding and
removing data elements
• A classic analogy is of a stack of trays in a cafeteria;
trays are removed from the top and placed back on the
top
“A stack is a sequential collection of elements into which
new elements are inserted and from which, elements are
deleted only at one end”

4
Stacks
• In a stack, the very first tray in the pile is the last one to
be removed
• For this reason, stacks are also known as last-in first-
out (LIFO) structures

5
Stacks

• We can only remove items that are available,


and can’t add more items if there is no room.

• We can define the stack in terms of operations


that change it (add/remove elements) or report
its status (full or empty)

6
Stacks
• These operations are:

7
Stacks

• Stacks are particularly useful in situations where data


have to be stored and processed in reverse order
• There are numerous applications of this
– Evaluating expressions and parsing syntax
– Balancing delimiters in program code
– Converting numbers between bases
– Processing financial data
– Backtracking algorithms

8
Stacks
• A stack can be represented using an array

• A stack can be represented using a singly linked list

head(top)
9
Stacks
• Stack representation with Array
typedef int T;
const int MAXSIZE = 10;
struct Stack
{
T theArray[MAXSIZE]; // array of elements in stack
int topOfStack; // the top position
};

10
Stacks
• Stack representation with Array using pointer
typedef int T;
struct Stack
{
T * theArray; // the pointer points to the array
int topOfStack; // the top position
};

11
Stacks
• Example: Stack representation with Array

12
Stacks

Algorithm to insert (push) an item to the stack

13
Stacks

Algorithm to delete (pop) the top element from the stack

14
Stacks

Example: Give two following stacks

Which operations (push(S, item)/pop(S, item) need to be


performed to get the second stack from the first one?

15
Stacks

Example: Find the top element of the Stack after


performing these operations:

push(15); push(13); pop(); push(14); push(16); pop()

16
Stacks

Example:

Write a program to solve these problems:

1. Create a stack to store integer elements (using an array


with maxsize is 15)

2. Add the elements to the stack (check if the stack is full)

3. Print all elements in stack

4. Check if the stack is empty

17
Stacks – applications in evaluating expression
This form is most suitable
for a computer to calculate any
expression

Arithmetic Expressions

Prefix Notation Infix Notation Postfix Notation

operator Op1 Op2 Op1 operator Op2 Op1 Op2 operator

+ab a+b ab+

We are familiar with


this form

18
Stacks

Applying stack in evaluating a post-fix expression


1. Push “(“ onto stack & add “)” to the end of Q.
2. Traverse each element in stack from the left to the right:
3. If the element is an operand then add it to P.
4. If the element is left parenthesis “(“ then push it onto the stack.
5. If the element is an operator then:
a) Repeatedly pop from stack (until the element on top of
the stack has higher or same precedence than the operator currently
scanned) and add it to P.
b) Add the operator to stack.
6. If the element is a right parenthesis “)” then:
a) Repeatedly pop from stack and add to P each operator
until a left parenthesis “(“ is found
b) Pop the left parenthesis from the stack.

19
Stacks

Applying stack in evaluating a post-fix expression


(Binary expression)

Traverse each element in expression from the left to


the right:
1. If the element is an operand then add it to stack.
2. If the element is an operator then:
- Pop two elements from the stack P and apply the
operator on two obtained elements.
- Put the result to the stack
20
Stacks

Example: Evaluating the following post-fix expression


6523+8∗+3+∗

Push four fist operands (6, 5, 2, 3) to a stack

21
Stacks
6523+8∗+3+∗
• Read “+”, pop two elements from stack (3 and 2)
• Apply the operator (+) on these two items
• The result is 5
• Add this to stack

22
23

6523+8∗+3+∗
• Push 8 to stack.
24

6523+8∗+3+∗
• Read “∗”:
- Pop two elements (8 and 5)
- Apply multiple operator to get 40
- Push 40 to stack.
25

6523+8∗+3+∗
26

6523+8∗+3+∗
27

6523+8∗+3+∗
28

6523+8∗+3+∗

The time complexity: O(n)


Stacks

Exercise: Evaluating the following post-fix expression

3 5 7 * + 12 %

29
Queues

• A queue, like a stack, is a restricted access linear data


structure
• Unlike a stack, both ends are involved, with additions
restricted to one end (the rear) and deletions to the other
(the front)
• Since an item added to the queue must migrate from the
rear to the front before it is removed, items are removed
in the order they are added
• For this reason, queues are also known as first-in first-
out (FIFO) structures

30
Queues
Examples of a queue

31
Queues

• The functions of a queue are similar to those of a stack

32
Queues
• Algorithm to insert an item to rear of a queue by using an array

33
Queues
• Algorithm to delete from the front of a queue by using an array

Algorithm: DEQUEUE (Q, ITEM)


[Q is an array represent queue and ITEM is
inserted item]
1. [Check underflow]
If Rear = Front then
a) Print: Queue is Empty
b) Return
2. Set Front = Front+1
3. ITEM = Q[Front]
4. If Rear = Front then
Set Front = Rear = -1
5. Return

34
Queues

• Example

35
Queues

Fig. 4.7 A series of operations executed on a queue

• One way a queue may be implemented utilizes an array,


although care must be exercised
• In particular, as items are removed from the queue,
spaces open up in the front of the array, which should
not be wasted
• So items may be added to the “end” of the queue at the
beginning of the array
• This treats the array as though it were circular

36
Queues

Two possible configurations in an array implementation of a queue when the queue is full; (c) the same queue viewed as a circular
array

• As the circular array illustrates, the queue is full if the first and
last elements are adjacent
• However, based on the actual array, this can occur in two
situations
– The first element is in the first location, and the last element in the last
– The first element is immediately after the last element

37
Queues

• Queues are used in a wide variety of applications,


especially in studies of service simulations

• This has been analyzed to such an extent that a very


advanced body of mathematical theory, called queuing
theory, has been developed to deal with it

38
Queues

• Example of a circular queue

(1) 12 35 (2) 17 18 35 26

front back back front


Which operations (insert/delete) need to be performed
to get the second queue from the first one?

39
Queues

• Example: Find the element at the front of the queue


after performing these operations:

EnQueue(20); EnQueue(15); DeQueue(); EnQueue(23); DeQueue(); EnQueue(6)

40
Queues

Given a string S = “This**is***an*example**”.


Read the characters in S from left to right;
- If you read the character X differs from ‘*’: Add X to
the queue Q
- If you read ‘*’: delete an element from Q,
What is the element at the front of Q?
What happens if we use a STACK instead of a queue
(find element at the top of stack)?

41
Queues

Exercise: Use a singly linked list to present a queue


struct Node
{
int elem;
Node * next;
};

struct Queue
{
Node * front;
Node * back;
int size;
};

Write a program to:


1. Create a queue to store integer elements (size is 10)
2. Add the elements to the queue (check if the queue is full)
3. Delete two elements from the queue
4. Print all the elements in the queue 42
Priority Queues

• In some circumstances, the normal FIFO operation of a queue


may need to be overridden
• This may occur due to priorities that are associated the
elements of the queue that affect the order of processing
• In cases such as these, a priority queue is used, where the
elements are removed based on priority and position

This child may


be priority to
be the first

43
Priority Queues

A Priority Queue is a collection of elements such that each


element has been assigned a priority and the elements are
arranged on the basis of priority. The order in which
elements are deleted and processed comes from the
following rules:
i) The element having a higher priority is processed
before any elements of lower priority.
ii) The two elements that have the same priority are
processed according to the order in which that are
inserted into the priority queue

44
Priority Queues

Example Descending priority queue

Insert 4

Insert 1

Insert 8

Insert 7

Insert 3

45
Priority Queues

• The difficulty in implementing such a structure is trying to


accommodate the priorities while still maintaining
efficient enqueuing and dequeuing

• Elements typically arrive randomly, so their order


typically reflects no specific priority

46
Priority Queues

Time complexity of different operation with different


representations

Using a complete binary


search tree

47
EXERCISES

48
EXERCISES

49
Queues (assignment-submit before 16/10)

Example:

Write a program to solve these problems:

1. Create a stack to store integer elements (using a singly


linked list)

2. Add the elements to the stack

3. Print all elements in stack

4. Check if the stack is empty

50

You might also like