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

Chapter 5 Stack and Queue - Teacher

data structure and algorithm

Uploaded by

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

Chapter 5 Stack and Queue - Teacher

data structure and algorithm

Uploaded by

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

Chapter five

Stacks And
Queues

1
Part one

Stacks its Stack


Applications

2
Quick Introduction

 Stacks are linear lists.


 All deletions and insertions occur at one end of
the stack known as the TOP.
 Data going into the stack first, leaves out last.
 Stacks are also known as LIFO data structures
(Last-In, First-Out).

3
Basic Stack Operations

 Push – Adds an item to the top of a stack.

 Pop – Removes an item from the top of the stack


and returns it to the user.

 Peek – Copies the top item of the stack and


returns it to the user; the item is not removed,
hence the stack is not altered.

4
Abstract data type: Stack
 There are many times where it is useful to use a list
in a way where we always add to the end, and also
always remove from the end.
 The last element put into the list will be the first
element we take out of the list.
 Last-In, First-Out ("LIFO")
 stack: a more restricted List with the following
constraints:
 Elements are stored by order of insertion from
"bottom" to "top“.
 Items are added to the top.
 Only the last element added onto the stack (the
top element) can be accessed or removed.
 Goal: every operation on a stack should be O(1).
 Stacks are straightforward to implement in several
different ways, and are very useful.
 Operations on a stack
 push: add an element to the top.
 pop: remove and return the element at5 5
the top.
Stack … (continued)

 peek: return (but not remove) top element;


pop or peek on an empty stack causes an exception.
 Other operations: isEmpty, size

push(a)
push(b)
pop()

6
6
Stack … (continued)
Stack features:
 ORDERING: maintains order elements were added
(new elements are added to the end by default).
 OPERATIONS:
 Add element to end of stack ('push')
 Remove element from end of stack ('pop')
 Examine element at end of stack ('peek')
 Clear all elements from stack (‘makeEmpty’)
 Check whether stack is empty or not (‘isEmpty’)
 Find size of stack (‘getSize’)
 All of these operations are efficient! O(1).
Stacks in computer science
 the lowly stack is one of the most important data structures
in all of computer science
 Function/method calls are placed onto a stack.
 Compilers use stacks to evaluate expressions.
 Stacks are great for reversing things, matching up7 related
pairs of things, and backtracking algorithms. 7
Stack … (continued)

 Stacks in programming problems:


 Reverse letters in a string, reverse words
in a line, or reverse a list of numbers.
 Find out whether a string is a palindrome.

Examine a file to see if its braces {}
and other operators match.

8
8
Additional Notes
 Stacks structures are usually implemented using
arrays or linked lists.

 For both implementations, the running time is


O(1).

 We will be examining common Stack Applications.

9
Stack Applications
Reversing Data:
 We can use stacks to reverse data.
(example: files, strings).
 Very useful for finding palindromes.
 Consider the following pseudo code:
1) read (data)
2) loop (data not EOF and stack not full)
1) push (data)
2) read (data)
3) Loop (while stack notEmpty)
1) pop (data)
10
2) print (data)
 Converting Decimal to Binary:
 Consider the following pseudo code:
1) Read (number)
2) Loop (number > 0)
1) digit = number modulo 2
2) print (digit)
3) number = number / 2

11
 The problem with this code is that it will print the
binary number backwards.

Example: 19 becomes 11001000 instead of 00010011


 To remedy this problem, instead of printing the
digit right away, we can push it onto the stack.

 Then after the number is done being converted, we


pop the digit out of the stack and print it.

12
Infix to Postfix Conversion

Infix(a+b):-a natural way of expressing mathematical


expression.
 There are other ways of representing the same expression:

 Prefix: + a b
 Postfix: a b +

13
 In high level languages, infix notation cannot be used to evaluate expressions.

 We must analyze the expression to determine the order in which we evaluate it.

 A common technique is to convert a infix notation into postfix notation, then evaluating it.

14
Rules:
• Operands immediately go directly to output
• Operators are pushed into the stack
(including parenthesis)
 Check to see if stack top operator is less than
current operator
 If the top operator is less than, push the current
operator onto stack
 If the top operator is greater than (or equal to)
the current, pop top operator and append on
postfix notation, push current operator onto
stack.
 If we encounter a right parenthesis, pop from
stack until we get matching left parenthesis. Do
not output parenthesis.
15
Precedence Priority of
operators:
 Priority 4: ‘(‘ - only popped if a matching
‘)’ is found.
 Priority 3: All unary operators ( sin,
cosin,….)
 Priority 2: / *
 Priority 1: + -

16
Example 1:
A + B * C - D / E

Infix Stack(bottom->top) Postfix

A + B * C - D / E empty empty
 + B * C - D / E empty A
b) B * C - D / E + A
c) * C - D / E + A B
d) C - D / E + * A B
e) - D / E + * A B C
f) D / E + A B C *
g) / E - A B C *+
h) E - / A B C *+ D
i) - / A B C *+
D E
j) empty A B C *+ D E / -

17
Example 2:
A * B - ( C + D ) + E

Infix Stack(bottom->top) Postfix

A * B - ( C + D ) + E empty empty
a) * B - ( C + D ) + E empty A
c) B - ( C + D ) + E * A
d) - ( C + D ) + E * A B
e) - ( C + D ) + E empty A B *
f) ( C + D ) + E - A B *
g) C + D ) + E - ( A B *
h) + D ) + E - ( A B * C
i) D ) + E - ( + A B * C
j) ) + E - ( + A B * C D
k) + E - A B * C D +
l) + E empty A B * C D + -
m) E + A B * C D + -
n) + A B * C D + - E
18
o) empty A B * C D + - E +
Example 3:
a + b * c + ( d * e + f ) * g
Infix Stack(bottom->top) Postfix
a+b*c+(d*e+f)*g empty empty
a) +b*c+(d*e+f)*g empty a
b) b*c+(d*e+f)*g + a
c) *c+(d*e+f)*g + a b
d) c+(d*e+f)*g + * a b
e) +(d*e+f)*g + * a b c
f) +(d*e+f)*g + a b c *
g) +(d*e+f)*g empty a b c * +
h) (d*e+f)*g + a b c * +
i) d*e+f)*g + ( a b c * +
j) *e+f)*g + ( a b c * + d
k) e+f)*g + ( * a b c * + d
l) +f)*g + ( * a b c * + d e
m) f)*g + ( + a b c * + d e *
n) )*g + ( + a b c * + d e * f
o) *g + a b c * + d e * f +
19
p) g + * a b c * + d e * f +
q) + * a b c * + d e * f + g
 Postfix Evaluation
Pseudo code:
Operand: push
Operator: pop 2 operands, do the math, push result
back onto stack
1 2 3 + *
Postfix Stack( bot -> top )
a) 1 2 3 + *
b) 2 3 + * 1
c) 3 + * 1 2
d) + * 1 2 3
e) * 1 5 //5 from
2+3 20
f) 5 // 5 from 1 * 5
 Page-visited history in a Web browser
 To Undo and Redo in a text editor:
Pseudocode:
Accept the command
if(command==Undo)
push_RS(pop_US( ))
else if(command==Redo)
push_US(pop_RS())
else
pushUS(command)

21
Implementation of Stacks
 Stack data structure can be implemented in two ways.
 Arrays (static: the size of stack is given initially)
 Linked lists (dynamic: never become full)

The algorisms for Basic Operations:


Push()
{
if there is room {
put an item on the top of the stack
}
else
give an error message
}

22
Conti……
Pop() {
if stack not empty {
return the value of the top
item(optional)
remove the top item from the stack
}
else {
give an error message
}
}
createStack() {
remove existing items from the stack
initialize the stack to empty
} 23
Array Implementation of Stacks: Push
 The PUSH operation
 Addition of an element is known as the PUSH operation. So, if
an array is given to you, which is supposed to act as a STACK,
you know that it has to be a STATIC Stack; meaning, data will
overflow if you cross the upper limit of the array.

Algorithm:

 Step 1: Create stack data structure and set top=-1 globally.

 Step 2: Check whether stack is FULL. (top == SIZE-1)

 Step 3: If it is FULL, then display “Stack is FULL!!!


Insertion is not possible!!!" and terminate the function.

 Step 4: If it is NOT FULL, then increment top value by one


24
(top++) and set stack[top] = data/value.
C++ function segment for push operation using array

const int size=5;


int stacks[size]; Global Variables
int top=-1;
void push(int data){
if(top==size-1)
cout<<"stack is full\n";
else {
top=top+1;
stacks[top]=data;
cout<<stacks[top]<<" pushed\n";
}
}

25
Array Implementation of Stacks:
Pop
 POP Operation
 POP is the synonym for delete when it comes to Stack.
 So, if you're taking an array as the stack, remember that
you'll return an error message, "Stack underflow", if an
attempt is made to Pop an item from an empty Stack.
 Algorithm
 Step-1: Check If the Stack is empty then give the alert
"Stack underflow" and quit; or else go to step-2
 Step-2: Hold the value for the element pointed by the
TOP
 Put a NULL value instead
 Decrement the TOP by 1

26
C++ function segment for POP operation
using array
void pop(){
if(top==-1) {
cout<<"stack is Empty\n";
}
else {
int del_val=stacks[top];
stacks[top]=NULL;
top--;
cout<<del_val<<"popped out\n";
}
}

27
Display stack elements of array

We can use the following steps to display the elements


of a stack...
 Step 1: Check whether stack is EMPTY. (top == -
1)
 Step 2: If it is EMPTY, then display "Stack is
EMPTY!!!" and terminate the function.
 Step 3: If it is NOT EMPTY, then define a variable 'i'
and initialize with top. Display stack[i] value and
decrement i value by one (i--).
 Step 3: Repeat above step until i value becomes '0'.

28
C++ function segment for displaying data
elements of stack

Void peek(){
if(top==-1) {
cout<<"stack is empty\n";
}
else {
cout<<"stack elements are:\n";
for(int I = top; i>=0; i--) {
cout<<stacks[i] <<endl;
}
}
}
29
Linked List Implementation of Stacks:
PUSH
 It’s very similar to the insertion operation in a
dynamic singly linked list.
 The only difference is that here you'll add the
new element only at the end or top of the
list, which means addition can happen only
from the TOP.
 Since a dynamic list is used for the stack, the
Stack is also dynamic, means it has no prior
upper limit set.
 So, we don't have to check for the Overflow
condition at all.
30
Steps to push data to stack using singly
linked list
 Step 1: Create a newNode with given value.
 Step 2: Check whether stack
is Empty (top == NULL)
 Step 3: If it is Empty, then set newNode →
next = NULL.
 Step 4: If it is Not Empty, then set newNode →
next = top.
 Step 5: Finally, set top = newNode.

31
C++ code for push
using namespace node *top=NULL,;
std;
void push(){
struct node{
node *newNode;
int data;
newNode=new node;
node*next;
cout<<"enter new node
}; data\n";
cin>>newNode->data;
if(top==NULL)
top->next=NULL;
else{
newNode->next=top;
top=newNode;
}
} 32
Steps to pop data to stack using
singly linked list
We can use the following steps to delete a node from the
stack...
 Step 1: Check whether stack is Empty (top == NULL).
 Step 2: If it is Empty, then display "Stack is Empty!!!
Deletion is not possible!!!" and terminate the function
 Step 3: If it is Not Empty, then define a Node pointer
'temp' and set it to 'top'.
 Step 4: Then set 'top = top → next'.
 Step 7: Finally, delete 'temp' (delete temp).

33
C++ code for pop
void pop(){
node*temp;
temp=top;
if(top==NULL){
cout<<"stack underflow!!! deletion not possible\n";
}
else{
top=temp->next;
temp->next=NULL;
delete temp;
}
}

34
C++ code for display
void display(){
node *temp;
if(top==NULL){
cout<<"stack empty\n";
}
else{
cout<<"stack Elements are:\n";
temp=top;
while(temp!=NULL){
cout<<temp->data<<endl;
temp=temp->next;
}
}
} 35
Thanks

? 36
Part Two

37
Queue

Abstract data type: Queue


 Many times, we use a list in a way where we always
add to the end, and always remove from the front.
 The first element put into the list will be the first
element we take out of the list:
 First-In, First-Out ("FIFO")
 Queue: a more restricted List with the
following constraints:
 Elements are stored by order of insertion from front
to back.
 Items can only be added to the back of the queue.
 Only the front element can be accessed or removed.
 Goal: every operation on a queue should be
O(1).

38
Queue … (continued)

Operations on a queue
 Offer or enqueue: add an element to the back.
 Remove or dequeue: remove and return the element at
the front.
 peek: return (but not remove) front element:
 peek on an empty queue returns null.
 Other operations: isEmpty, size.

Queue features
 ORDERING: maintains order elements were
added (new elements are added to the end by
default). 39
Queue … (continued)
 OPERATIONS:
 Add element to end of list ('offer'
or 'enqueue').
 Remove element from beginning
of list ('remove' or 'dequeue')
examine element at beginning of
list ('peek').
 Clear all elements.
 is empty, get size.
 All of these operations are
efficient! O(1).
40
The Queue Operations
A queue is like a line of people waiting
for a bank teller. The queue has a front
and a rear.

$ $

Front

Rear
The Queue Operations
 Newpeople must enter the
queue at the rear. it is usually
called an enqueue operation.

$ $

Front

Rear 42
The Queue Operations
 When an item is taken from the
queue, it always comes from the
front. it is usually called a
dequeue operation.
$ $

Front

Rear
Array Implementation of
Queue

44
A queue can be implemented with an
array, as shown here. For example,
this queue contains the integers 4 (at
the front), 8 and 6 (at the rear).

[0] [1] [2] [3] [4] [5] ...


4 8 6

An array of integers
to implement a We don't care what's in
queue of integers this part of the array.

45
1. Simple Array Implementation
of Queue

 The easiest implementation 3 size


also keeps track of the number
of items in the queue (Queue 0 first
Size) and the index of the first
element (at the front of the
2 last
queue), the last element (at
the rear).
[0] [1] [2] [3] [4] [5] ...

4 8 6
46
Front Rear
A Dequeue Operation
 When an element leaves the
queue, size is decremented, and
first changes, too. 2 size

1 first

2 last
[0] [1] [2] [3] [4] [5] ...

4 8 6

Front Rear
An Enqueue Operation

 When an element enters the 3 size


queue, size is incremented,
and last changes, too. 1 first

3 last

[0] [1] [2] [3] [4] [5] ...

8 6 2
48

Front Rear
2. Circular Array Implementation
of Queue
 There is special behaviour at the end
of the array. For example, suppose we 3 size
want to add a new element to this
queue, where the last index is [5]:
3 first

5 last

[0] [1] [2] [3] [4] [5]


2 6 1
49

Front Rear
An Enqueue Operation

 The new element goes at the front


of the array (if that spot isn’t 4 size
already used):
3 first

0 last
[0] [1] [2] [3] [4] [5]
4 2 6 1
50
Rear
Front
Linked List
Implementation

51
A queue can also be implemented
with a linked list with both a head
(start) and a tail (end) pointer.
Enqueue:- is inserting a node at
the end of a linked list.
Dequeue:- is deleting the first
node in a linked list.

52
13 10 15
nul
l

head_ptr
tail_ptr
Types of Queue

54
Deque (pronounced as Deck)

 Is a Double Ended Queue.


 Insertion and deletion can occur at either end.
 Has the following basic operations:
EnqueueFront:– inserts data at the front of a
list.
DequeueFront:– deletes data at the front
of a list.
EnqueueRear:– inserts data at the end of
a list.
DequeueRear:– deletes data at the end of a
list.
55
 Implementation is similar to that of
queue.
 Is best implemented using doubly
linked list.

Front Rear

DequeueFront EnqueueFront DequeueRear EnqueueRear


56
Priority Queue
 Isa queue where each data has an
associated key that is provided at the
time of insertion.

 Dequeue operation deletes data


having highest priority in the list.

 One of the previously used dequeue or


enqueue operations has to be
modified.
57
Example: Consider the following queue
of persons where females have higher
priority than males (gender is the key
to give priority).

Abebe Alemu Aster Belay Kedir Meron Yonas


Male Male Female Male Male Female Male

58
Dequeue()- deletes Aster.
Abebe Alemu Belay Kedir Meron Yonas
Male Male Male Male Female Male

Dequeue()- deletes Meron


Abebe Alemu Belay Kedir Yonas
Male Male Male Male Male

59
 Now the queue has data having equal
priority and dequeue operation deletes
the front element like in the case of
ordinary queues.

 Dequeue():- deletes Abebe

Alemu Belay Kedir Yonas


Male Male Male Male
 Dequeue():- deletes Alemu

Belay Kedir Yonas


Male Male Male

 Thus,
in the above example the
implementation of the dequeue
operation need to be modified.

61
Demerging Queues:
Is the process of creating two
or more queues from a single
queue.
Used to give priority for some
groups of data

62
Example: The following two
queues can be created from the
above priority queue.

Aster Meron
Female Female

Abebe Alemu Belay Kedir Yonas


Male Male Male Male Male
Algorithm:
create empty females and males queue
while (PriorityQueue is not empty)
{
Data=DequeuePriorityQueue();//delete data at
the front
if(gender of Data is Female)
EnqueueFemale(Data);
else
EnqueueMale(Data);
}

64
Merging Queues:
Is the process of creating a
priority queue from two or
more queues.
The ordinary dequeue
implementation can be used to
delete data in the newly
created priority queue.
65
Example: The following two queues
(females queue has higher priority
than the males queue) can be
merged to create a priority queue.

Aster Meron Abebe Alemu Belay Kedir Yonas


Female Female Male Male Male Male Male

Aster Meron Abebe Alemu Belay Kedir Yonas


Female Female Male Male Male Male Male
Algorithm:
create an empty priority queue
while(FemalesQueue is not empty)
EnqueuePriorityQueue(DequeueFemalesQueue());
while(MalesQueue is not empty)

EnqueuePriorityQueue(DequeueMalesQueue());

67
Application of Queues

I. Access to shared resources


(Example: printer)
Print()
{
EnqueuePrintQueue(Document)
}
EndOfPrint()
{
DequeuePrintQueue()
}
Application of Queues
(...Continued)

II. Disk Driver:-maintains a queue of disk


input/output requests.

III. Task scheduler in multiprocessing


system maintains priority queues of processes.

IV. Telephone calls in a busy environment


maintains a queue of telephone calls.
69
End of Chapter Five

Thanks

? 70

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy