6-Stack and Queue
6-Stack and Queue
1
Main contents
• Stacks
• Evaluation of Expression
• Queues
• Circular Queue
• Priority Queues
2
Introduction
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
6
Stacks
• These operations are:
7
Stacks
8
Stacks
• A stack can be represented using an array
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
13
Stacks
14
Stacks
15
Stacks
16
Stacks
Example:
17
Stacks – applications in evaluating expression
This form is most suitable
for a computer to calculate any
expression
Arithmetic Expressions
18
Stacks
19
Stacks
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+∗
3 5 7 * + 12 %
29
Queues
30
Queues
Examples of a queue
31
Queues
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
34
Queues
• Example
35
Queues
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
38
Queues
(1) 12 35 (2) 17 18 35 26
39
Queues
40
Queues
41
Queues
struct Queue
{
Node * front;
Node * back;
int size;
};
43
Priority Queues
44
Priority Queues
Insert 4
Insert 1
Insert 8
Insert 7
Insert 3
45
Priority Queues
46
Priority Queues
47
EXERCISES
48
EXERCISES
49
Queues (assignment-submit before 16/10)
Example:
50