SlideShare a Scribd company logo
1 of 75
Stacks and Queues 
Trupti Agrawal 1
Stacks 
 Linear list. 
 One end is called top. 
 Other end is called bottom. 
 Additions to and removals from the top end only. 
Trupti Agrawal 2
Stack Of Cups 
top 
bottom 
E 
D 
C 
B 
A 
 Add a cup to the stack. 
top 
bottom 
F 
E 
D 
C 
B 
A 
• Remove a cup from new stack. 
• A stack is a LIFO list. 
Trupti Agrawal 3
Towers Of Hanoi/Brahma 
1 2 3 4 
A B C 
 64 gold disks to be moved from tower A to tower C 
 each tower operates as a stack 
 cannot place big disk on top of a smaller one 
Trupti Agrawal 4
Towers Of Hanoi/Brahma 
1 2 3 
A B C 
 3-disk Towers Of Hanoi/Brahma 
Trupti Agrawal 5
Towers Of Hanoi/Brahma 
1 2 
A B C 
 3-disk Towers Of Hanoi/Brahma 
3 
Trupti Agrawal 6
Towers Of Hanoi/Brahma 
1 2 3 
A B C 
 3-disk Towers Of Hanoi/Brahma 
Trupti Agrawal 7
Towers Of Hanoi/Brahma 
1 2 3 
A B C 
 3-disk Towers Of Hanoi/Brahma 
Trupti Agrawal 8
Towers Of Hanoi/Brahma 
1 2 3 
A B C 
 3-disk Towers Of Hanoi/Brahma 
Trupti Agrawal 9
Towers Of Hanoi/Brahma 
3 2 1 
A B C 
 3-disk Towers Of Hanoi/Brahma 
Trupti Agrawal 10
Towers Of Hanoi/Brahma 
A B C 
 3-disk Towers Of Hanoi/Brahma 
1 2 
3 
Trupti Agrawal 11
Towers Of Hanoi/Brahma 
A B C 
 3-disk Towers Of Hanoi/Brahma 
1 2 3 
• 7 disk moves Trupti Agrawal 12
Recursive Solution 
1 
A B C 
 n > 0 gold disks to be moved from A to C using B 
 move top n-1 disks from A to B using C 
Trupti Agrawal 13
Recursive Solution 
1 
A B C 
 move top disk from A to C 
Trupti Agrawal 14
Recursive Solution 
A B C 
 move top n-1 disks from B to C using A 
1 
Trupti Agrawal 15
Recursive Solution 
1 
A B C 
 moves(n) = 0 when n = 0 
 moves(n) = 2*moves(n-1) + 1 = 2n-1 when n > 0 
Trupti Agrawal 16
Towers Of Hanoi/Brahma 
 moves(64) = 1.8 * 1019 (approximately) 
 Performing 109 moves/second, a computer would take about 
570 years to complete. 
 At 1 disk move/min, the monks will take about 3.4 * 1013 years. 
Trupti Agrawal 17
Rat In A Maze 
Trupti Agrawal 18
Rat In A Maze 
 Move order is: right, down, left, up 
 Block positions to avoid revisit. 
Trupti Agrawal 19
Rat In A Maze 
 Move order is: right, down, left, up 
 Block positions to avoid revisit. 
Trupti Agrawal 20
Rat In A Maze 
 Move backward until we reach a square from which a forward 
move is possible. 
Trupti Agrawal 21
Rat In A Maze 
 Move down. 
Trupti Agrawal 22
Rat In A Maze 
 Move left. 
Trupti Agrawal 23
Rat In A Maze 
 Move down. 
Trupti Agrawal 24
Rat In A Maze 
 Move backward until we reach a square from which a forward 
move is possible. 
Trupti Agrawal 25
Rat In A Maze 
 Move backward until we reach a square from which a 
forward move is possible. 
• Move downwTarurptid Ag.rawal 26
Rat In A Maze 
 Move right. 
• Backtrack. Trupti Agrawal 27
Rat In A Maze 
 Move downward. 
Trupti Agrawal 28
Rat In A Maze 
 Move right. 
Trupti Agrawal 29
Rat In A Maze 
 Move one down and then right. 
Trupti Agrawal 30
Rat In A Maze 
 Move one up and then right. 
Trupti Agrawal 31
Rat In A Maze 
 Move down to exit and eat cheese. 
 Path from maze entry to current position operates as a stack. 
Trupti Agrawal 32
Stacks 
 Standard operations: 
 IsEmpty … return true iff stack is empty 
 IsFull … return true iff stack has no remaining capacity 
 Top … return top element of stack 
 Push … add an element to the top of the stack 
 Pop … delete the top element of the stack 
Trupti Agrawal 33
Stacks 
 Use a 1D array to represent a stack. 
 Stack elements are stored in stack[0] through stack[top]. 
Trupti Agrawal 34
Stacks 
a b c d e 
0 1 2 3 4 5 6 
 stack top is at element e 
 IsEmpty() => check whether top >= 0 
 O(1) time 
 IsFull() => check whether top == capacity – 1 
 O(1) time 
 Top() => If not empty return stack[top] 
 O(1) time 
Trupti Agrawal 35
Derive From arrayList 
a b c d e 
0 1 2 3 4 5 6 
 Push(theElement) => if full then either error or 
increase capacity and then add at stack[top+1] 
 Suppose we increase capacity when full 
 O(capacity) time when full; otherwise O(1) 
Pop() => if not empty, delete from stack[top] 
 O(1) time 
Trupti Agrawal 36
Push 
a b c d e 
0 1 2 3 4 
top 
 void push(element item) 
 {/* add an item to the global stack */ 
 if (top >= MAX_STACK_SIZE - 1) 
 StackFull(); 
 /* add at stack top */ 
 stack[++top] = item; 
 } 
 
Trupti Agrawal 37
Pop 
a b c d e 
0 1 2 3 4 
top 
 element pop() 
 { 
 if (top == -1) 
 return StackEmpty(); 
 return stack[top--]; 
 } 
Trupti Agrawal 38
StackFull() 
void StackFull() 
{ 
fprintf(stderr, “Stack is full, cannot add 
element.”); 
exit(EXIT_FAILURE); 
} 
Trupti Agrawal 39
StackFull()/Dynamic Array 
 Use a variable called capacity in place of 
MAX_STACK_SIZE 
 Initialize this variable to (say) 1 
 When stack is full, double the capacity using REALLOC 
 This is called array doubling 
Trupti Agrawal 40
StackFull()/Dynamic Array 
void StackFull() 
{ 
REALLOC(stack, 2*capacity*sizeof(*stack); 
capacity *= 2; 
} 
Trupti Agrawal 41
Complexity Of Array 
Doubling 
 Let final value of capacity be 2k 
 Number of pushes is at least 2k-1+ 1 
 Total time spent on array doubling is S1<=i=k2i 
 This is O(2k) 
 So, although the time for an individual push is 
O(capacity), the time for all n pushes remains O(n)! 
Trupti Agrawal 42
Queues 
 Linear list. 
 One end is called front. 
 Other end is called rear. 
 Additions are done at the rear only. 
 Removals are made from the front only. 
Trupti Agrawal 43
Bus Stop Queue 
Bus 
Stop 
front 
rear 
rear rear rear rear 
Trupti Agrawal 44
Bus Stop Queue 
Bus 
Stop 
front 
rear 
rear rear 
Trupti Agrawal 45
Bus Stop Queue 
Bus 
Stop 
front 
rear 
rear 
Trupti Agrawal 46
Bus Stop Queue 
Bus 
Stop 
front 
rear 
rear 
Trupti Agrawal 47
Revisit Of Stack Applications 
 Applications in which the stack cannot be replaced 
with a queue. 
 Parentheses matching. 
 Towers of Hanoi. 
 Switchbox routing. 
 Method invocation and return. 
 Try-catch-throw implementation. 
 Application in which the stack may be replaced with a 
queue. 
 Rat in a maze. 
 Results in finding shortest path to exit. 
Trupti Agrawal 48
Queue Operations 
 IsFullQ … return true iff queue is full 
 IsEmptyQ … return true iff queue is empty 
 AddQ … add an element at the rear of the queue 
 DeleteQ … delete and return the front element of the queue 
Trupti Agrawal 49
Queue in an Array 
 Use a 1D array to represent a queue. 
 Suppose queue elements are stored with the front element in 
queue[0], the next in queue[1], and so on. 
Trupti Agrawal 50
Queue in an Array(Linear Queue) 
a b c d e 
0 1 2 3 4 5 6 
 DeleteQ() => delete queue[0] 
 O(queue size) time 
 AddQ(x) => if there is capacity, add at right end 
 O(1) time 
Trupti Agrawal 51
Circular Array(Circular Queue) 
 Use a 1D array queue. 
queue[] 
• Circular view of array. 
[0] 
[1] 
[2] [3] 
[4] 
[5] 
Trupti Agrawal 52
Circular Array 
• Possible configuration with 3 elements. 
[0] 
[1] 
[2] [3] 
[4] 
[5] 
A B 
C 
Trupti Agrawal 53
Circular Array 
• Another possible configuration with 3 
elements. 
[0] 
[1] 
[2] [3] 
[4] 
[5] 
B A 
C 
Trupti Agrawal 54
Circular Array 
• Use integer variables front and rear. 
– front is one position counterclockwise from first 
element 
– rear gives position of last element 
[0] 
[1] 
[2] [3] 
[4] 
[5] 
A B 
C 
front 
rear 
[0] 
[1] 
[2] [3] 
[4] 
[5] 
B A 
C 
front 
rear 
Trupti Agrawal 55
Add An Element 
[0] 
[1] 
[2] [3] 
[4] 
[5] 
A B 
C 
front 
rear 
• Move rear one clockwise. 
Trupti Agrawal 56
Add An Element 
• Move rear one clockwise. 
• Then put into queue[rear]. 
[0] 
[1] 
[2] [3] 
[4] 
[5] 
A B 
C 
front 
D 
rear 
Trupti Agrawal 57
Delete An Element 
[0] 
[1] 
[2] [3] 
[4] 
[5] 
A B 
C 
front 
rear 
• Move front one clockwise. 
Trupti Agrawal 58
Delete An Element 
• Then extract from queue[front]. 
[0] 
[1] 
[2] [3] 
[4] 
[5] 
A B 
C 
front 
rear 
• Move front one clockwise. 
Trupti Agrawal 59
Moving rear Clockwise 
• rear++; 
if (rear = = capacity) rear = 0; 
front rear 
[0] 
[1] 
[2] [3] 
[4] 
[5] 
A B 
C 
• rear = (rear + 1) % capacity; 
Trupti Agrawal 60
Empty That Queue 
[0] 
[1] 
[2] [3] 
[4] 
[5] 
B A 
C 
front 
rear 
Trupti Agrawal 61
Empty That Queue 
[0] 
[1] 
[2] [3] 
[4] 
[5] 
B 
C 
front 
rear 
Trupti Agrawal 62
Empty That Queue 
[0] 
[1] 
[2] [3] 
[4] 
[5] 
C 
front 
rear 
Trupti Agrawal 63
Empty That Queue 
[0] 
rear 
[1] 
[2] [3] 
[4] 
[5] 
front 
Trupti Agrawal 64
Dequque 
 In computer science, a double-ended queue (dequeue, 
often abbreviated to deque) is an abstract data type that 
generalizes a queue, for which elements can be added to 
or removed from either the front (head) or back (tail). 
 It is also often called a head-tail linked list, 
Trupti Agrawal 65
Dequque [Cont…] 
 This differs from the queue abstract data type or First-In- 
First-Out List (FIFO), where elements can only be added to 
one end and removed from the other. This general data 
class has some possible sub-types: 
 An input-restricted deque is one where deletion can be 
made from both ends, but insertion can be made at one end 
only. 
 An output-restricted deque is one where insertion can be 
made at both ends, but deletion can be made from one end 
only 
Trupti Agrawal 66
Dequque [Cont…] 
 Both the basic and most common list types in 
computing, queues and stacks can be considered 
specializations of deques, and can be implemented using 
deques. 
Trupti Agrawal 67
Applications of stacks: Conversion form 
infix to postfix and prefix 
expressions 
 There are a number of applications of stacks such as: 
 To print characters/string in reverse order. 
 Check the parentheses in the expression. 
 To evaluate the arithmetic expressions such as, infix, prefix 
and postfix. 
Trupti Agrawal 68
 Arithmetic expression: 
An expression is defined as a number of operands or data 
items combined using several operators. There are 
basically three types of notations for an expression: 
1) Infix notation 
2) Prefix notation 
3) Postfix notation 
(Main advantage of postfix and prefix notation are no need 
to use brackets) 
Trupti Agrawal 69
 Infix notation: It is most common notation in which, 
the operator is written or placed in-between the two 
operands. For eg. The expression to add two numbers 
A and B is written in infix notation as: 
 A+ B 
• A and B : Operands 
• + : Operator 
 In this example, the operator is placed in-between the 
operands A and B. The reason why this notation is 
called infix. 
Trupti Agrawal 70
 Prefix Notation: It is also called Polish notation, 
named after in the honor of the mathematician Jan 
Lukasiewicz, refers to the notation in which the 
operator is placed before the operand as: +AB 
 As the operator ‘+’ is placed before the operands A and 
B, this notation is called prefix (pre means before). 
Trupti Agrawal 71
 Postfix Notation: In the postfix notation the 
operators are written after the operands, so it is 
called the postfix notation (post means after), it is 
also known as suffix notation or reverse polish 
notation. The above postfix if written in postfix 
notation looks like follows; AB+ 
Trupti Agrawal 72
 Notation Conversions: Let us take an expression A+B*C 
which is given in infix notation. To evaluate this expression 
for values 2, 3, 5 for A, B, C respectively we must follow 
certain rule in order to have right result. For eg. A+B*C = 
2+3*5 = 5*5 = 25!!!!!!!! 
 Is this the right result? No, this is because the multiplication 
is to be done before addition, because it has higher 
precedence over addition. This means that for an expression 
to be calculated we must have the knowledge of precedence 
of operators. 
Trupti Agrawal 73
Operator Precedence 
Operator Symbol Precedence 
Exponential $ Highest 
Multiplication/Division *,/ Next highest 
Addition/Substraction +,- Lowest 
Trupti Agrawal 74
THANK YOU…!!! 
Trupti Agrawal 75

More Related Content

What's hot (20)

Stacks and queue
Stacks and queueStacks and queue
Stacks and queue
 
Stack and its operations
Stack and its operationsStack and its operations
Stack and its operations
 
Queue Data Structure (w/ php egs)
Queue Data Structure (w/ php egs)Queue Data Structure (w/ php egs)
Queue Data Structure (w/ php egs)
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
stack presentation
stack presentationstack presentation
stack presentation
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
 
Stack
StackStack
Stack
 
Stacks
StacksStacks
Stacks
 
Stacks and Queue - Data Structures
Stacks and Queue - Data StructuresStacks and Queue - Data Structures
Stacks and Queue - Data Structures
 
Queues in C++
Queues in C++Queues in C++
Queues in C++
 
Stack - Data Structure
Stack - Data StructureStack - Data Structure
Stack - Data Structure
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Stack project
Stack projectStack project
Stack project
 
My lectures circular queue
My lectures circular queueMy lectures circular queue
My lectures circular queue
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURE
 
stack & queue
stack & queuestack & queue
stack & queue
 

Viewers also liked

Stack and Queue (brief)
Stack and Queue (brief)Stack and Queue (brief)
Stack and Queue (brief)Sanjay Saha
 
Queue in C, Queue Real Life of Example
Queue in C, Queue Real Life of ExampleQueue in C, Queue Real Life of Example
Queue in C, Queue Real Life of ExampleHitesh Kumar
 
bca data structure
bca data structurebca data structure
bca data structureshini
 
Ppt on Linked list,stack,queue
Ppt on Linked list,stack,queuePpt on Linked list,stack,queue
Ppt on Linked list,stack,queueSrajan Shukla
 
Engineering Drawing: Chapter 04 orthographic writing
Engineering Drawing: Chapter 04 orthographic writingEngineering Drawing: Chapter 04 orthographic writing
Engineering Drawing: Chapter 04 orthographic writingmokhtar
 
Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arorakulachihansraj
 
Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examplesgreatqadirgee4u
 
Queue as data_structure
Queue as data_structureQueue as data_structure
Queue as data_structureeShikshak
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data StructureZidny Nafan
 
Fotografia digital
Fotografia digitalFotografia digital
Fotografia digitaliros1998
 
Распространённые ошибки оценки производительности .NET-приложений
Распространённые ошибки оценки производительности .NET-приложенийРаспространённые ошибки оценки производительности .NET-приложений
Распространённые ошибки оценки производительности .NET-приложенийAndrey Akinshin
 
President joyce banda meeting with british prime minister david cameron
President joyce banda meeting with british prime minister david cameronPresident joyce banda meeting with british prime minister david cameron
President joyce banda meeting with british prime minister david cameronkabmebanda1
 
The Netherlands investment climate - Main tax features
The Netherlands investment climate - Main tax featuresThe Netherlands investment climate - Main tax features
The Netherlands investment climate - Main tax featuresLoyens & Loeff
 

Viewers also liked (20)

Ds 3
Ds 3Ds 3
Ds 3
 
STACKS AND QUEUES CONCEPTS
STACKS AND QUEUES CONCEPTSSTACKS AND QUEUES CONCEPTS
STACKS AND QUEUES CONCEPTS
 
Chapter03
Chapter03Chapter03
Chapter03
 
Stack and Queue (brief)
Stack and Queue (brief)Stack and Queue (brief)
Stack and Queue (brief)
 
Queue in C, Queue Real Life of Example
Queue in C, Queue Real Life of ExampleQueue in C, Queue Real Life of Example
Queue in C, Queue Real Life of Example
 
bca data structure
bca data structurebca data structure
bca data structure
 
Chapter gases chemistery
Chapter  gases chemisteryChapter  gases chemistery
Chapter gases chemistery
 
C Language Unit-7
C Language Unit-7C Language Unit-7
C Language Unit-7
 
Ppt on Linked list,stack,queue
Ppt on Linked list,stack,queuePpt on Linked list,stack,queue
Ppt on Linked list,stack,queue
 
Data structures
Data structuresData structures
Data structures
 
Engineering Drawing: Chapter 04 orthographic writing
Engineering Drawing: Chapter 04 orthographic writingEngineering Drawing: Chapter 04 orthographic writing
Engineering Drawing: Chapter 04 orthographic writing
 
Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arora
 
Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examples
 
Queue as data_structure
Queue as data_structureQueue as data_structure
Queue as data_structure
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Fotografia digital
Fotografia digitalFotografia digital
Fotografia digital
 
jejeje
jejejejejeje
jejeje
 
Распространённые ошибки оценки производительности .NET-приложений
Распространённые ошибки оценки производительности .NET-приложенийРаспространённые ошибки оценки производительности .NET-приложений
Распространённые ошибки оценки производительности .NET-приложений
 
President joyce banda meeting with british prime minister david cameron
President joyce banda meeting with british prime minister david cameronPresident joyce banda meeting with british prime minister david cameron
President joyce banda meeting with british prime minister david cameron
 
The Netherlands investment climate - Main tax features
The Netherlands investment climate - Main tax featuresThe Netherlands investment climate - Main tax features
The Netherlands investment climate - Main tax features
 

Similar to Stacks and queues

Similar to Stacks and queues (20)

LEC4-DS ALGO.pdf
LEC4-DS  ALGO.pdfLEC4-DS  ALGO.pdf
LEC4-DS ALGO.pdf
 
Unit 4 queue
Unit   4 queueUnit   4 queue
Unit 4 queue
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
 
Stack.pptx
Stack.pptxStack.pptx
Stack.pptx
 
Lecture 2d queues
Lecture 2d queuesLecture 2d queues
Lecture 2d queues
 
3.8 quick sort
3.8 quick sort3.8 quick sort
3.8 quick sort
 
LEC3-DS ALGO(updated).pdf
LEC3-DS  ALGO(updated).pdfLEC3-DS  ALGO(updated).pdf
LEC3-DS ALGO(updated).pdf
 
QUEUES
QUEUESQUEUES
QUEUES
 
Unit – iv queue
Unit – iv    queueUnit – iv    queue
Unit – iv queue
 
Queue
QueueQueue
Queue
 
Queue - Data Structure - Notes
Queue - Data Structure - NotesQueue - Data Structure - Notes
Queue - Data Structure - Notes
 
Queues presentation
Queues presentationQueues presentation
Queues presentation
 
Queue
QueueQueue
Queue
 
Stack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparationStack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparation
 
Stacks in DATA STRUCTURE
Stacks in DATA STRUCTUREStacks in DATA STRUCTURE
Stacks in DATA STRUCTURE
 
Lect-28-Stack-Queue.ppt
Lect-28-Stack-Queue.pptLect-28-Stack-Queue.ppt
Lect-28-Stack-Queue.ppt
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
 
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdfCEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
 
Queues & ITS TYPES
Queues & ITS TYPESQueues & ITS TYPES
Queues & ITS TYPES
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
 

More from Trupti Agrawal

More from Trupti Agrawal (7)

Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Searching algorithms
Searching algorithmsSearching algorithms
Searching algorithms
 
Searching algorithms
Searching algorithmsSearching algorithms
Searching algorithms
 
Linked list
Linked listLinked list
Linked list
 
Arrays
ArraysArrays
Arrays
 
Data structure and algorithm
Data structure and algorithmData structure and algorithm
Data structure and algorithm
 

Recently uploaded

internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 

Recently uploaded (20)

OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 

Stacks and queues

  • 1. Stacks and Queues Trupti Agrawal 1
  • 2. Stacks  Linear list.  One end is called top.  Other end is called bottom.  Additions to and removals from the top end only. Trupti Agrawal 2
  • 3. Stack Of Cups top bottom E D C B A  Add a cup to the stack. top bottom F E D C B A • Remove a cup from new stack. • A stack is a LIFO list. Trupti Agrawal 3
  • 4. Towers Of Hanoi/Brahma 1 2 3 4 A B C  64 gold disks to be moved from tower A to tower C  each tower operates as a stack  cannot place big disk on top of a smaller one Trupti Agrawal 4
  • 5. Towers Of Hanoi/Brahma 1 2 3 A B C  3-disk Towers Of Hanoi/Brahma Trupti Agrawal 5
  • 6. Towers Of Hanoi/Brahma 1 2 A B C  3-disk Towers Of Hanoi/Brahma 3 Trupti Agrawal 6
  • 7. Towers Of Hanoi/Brahma 1 2 3 A B C  3-disk Towers Of Hanoi/Brahma Trupti Agrawal 7
  • 8. Towers Of Hanoi/Brahma 1 2 3 A B C  3-disk Towers Of Hanoi/Brahma Trupti Agrawal 8
  • 9. Towers Of Hanoi/Brahma 1 2 3 A B C  3-disk Towers Of Hanoi/Brahma Trupti Agrawal 9
  • 10. Towers Of Hanoi/Brahma 3 2 1 A B C  3-disk Towers Of Hanoi/Brahma Trupti Agrawal 10
  • 11. Towers Of Hanoi/Brahma A B C  3-disk Towers Of Hanoi/Brahma 1 2 3 Trupti Agrawal 11
  • 12. Towers Of Hanoi/Brahma A B C  3-disk Towers Of Hanoi/Brahma 1 2 3 • 7 disk moves Trupti Agrawal 12
  • 13. Recursive Solution 1 A B C  n > 0 gold disks to be moved from A to C using B  move top n-1 disks from A to B using C Trupti Agrawal 13
  • 14. Recursive Solution 1 A B C  move top disk from A to C Trupti Agrawal 14
  • 15. Recursive Solution A B C  move top n-1 disks from B to C using A 1 Trupti Agrawal 15
  • 16. Recursive Solution 1 A B C  moves(n) = 0 when n = 0  moves(n) = 2*moves(n-1) + 1 = 2n-1 when n > 0 Trupti Agrawal 16
  • 17. Towers Of Hanoi/Brahma  moves(64) = 1.8 * 1019 (approximately)  Performing 109 moves/second, a computer would take about 570 years to complete.  At 1 disk move/min, the monks will take about 3.4 * 1013 years. Trupti Agrawal 17
  • 18. Rat In A Maze Trupti Agrawal 18
  • 19. Rat In A Maze  Move order is: right, down, left, up  Block positions to avoid revisit. Trupti Agrawal 19
  • 20. Rat In A Maze  Move order is: right, down, left, up  Block positions to avoid revisit. Trupti Agrawal 20
  • 21. Rat In A Maze  Move backward until we reach a square from which a forward move is possible. Trupti Agrawal 21
  • 22. Rat In A Maze  Move down. Trupti Agrawal 22
  • 23. Rat In A Maze  Move left. Trupti Agrawal 23
  • 24. Rat In A Maze  Move down. Trupti Agrawal 24
  • 25. Rat In A Maze  Move backward until we reach a square from which a forward move is possible. Trupti Agrawal 25
  • 26. Rat In A Maze  Move backward until we reach a square from which a forward move is possible. • Move downwTarurptid Ag.rawal 26
  • 27. Rat In A Maze  Move right. • Backtrack. Trupti Agrawal 27
  • 28. Rat In A Maze  Move downward. Trupti Agrawal 28
  • 29. Rat In A Maze  Move right. Trupti Agrawal 29
  • 30. Rat In A Maze  Move one down and then right. Trupti Agrawal 30
  • 31. Rat In A Maze  Move one up and then right. Trupti Agrawal 31
  • 32. Rat In A Maze  Move down to exit and eat cheese.  Path from maze entry to current position operates as a stack. Trupti Agrawal 32
  • 33. Stacks  Standard operations:  IsEmpty … return true iff stack is empty  IsFull … return true iff stack has no remaining capacity  Top … return top element of stack  Push … add an element to the top of the stack  Pop … delete the top element of the stack Trupti Agrawal 33
  • 34. Stacks  Use a 1D array to represent a stack.  Stack elements are stored in stack[0] through stack[top]. Trupti Agrawal 34
  • 35. Stacks a b c d e 0 1 2 3 4 5 6  stack top is at element e  IsEmpty() => check whether top >= 0  O(1) time  IsFull() => check whether top == capacity – 1  O(1) time  Top() => If not empty return stack[top]  O(1) time Trupti Agrawal 35
  • 36. Derive From arrayList a b c d e 0 1 2 3 4 5 6  Push(theElement) => if full then either error or increase capacity and then add at stack[top+1]  Suppose we increase capacity when full  O(capacity) time when full; otherwise O(1) Pop() => if not empty, delete from stack[top]  O(1) time Trupti Agrawal 36
  • 37. Push a b c d e 0 1 2 3 4 top  void push(element item)  {/* add an item to the global stack */  if (top >= MAX_STACK_SIZE - 1)  StackFull();  /* add at stack top */  stack[++top] = item;  }  Trupti Agrawal 37
  • 38. Pop a b c d e 0 1 2 3 4 top  element pop()  {  if (top == -1)  return StackEmpty();  return stack[top--];  } Trupti Agrawal 38
  • 39. StackFull() void StackFull() { fprintf(stderr, “Stack is full, cannot add element.”); exit(EXIT_FAILURE); } Trupti Agrawal 39
  • 40. StackFull()/Dynamic Array  Use a variable called capacity in place of MAX_STACK_SIZE  Initialize this variable to (say) 1  When stack is full, double the capacity using REALLOC  This is called array doubling Trupti Agrawal 40
  • 41. StackFull()/Dynamic Array void StackFull() { REALLOC(stack, 2*capacity*sizeof(*stack); capacity *= 2; } Trupti Agrawal 41
  • 42. Complexity Of Array Doubling  Let final value of capacity be 2k  Number of pushes is at least 2k-1+ 1  Total time spent on array doubling is S1<=i=k2i  This is O(2k)  So, although the time for an individual push is O(capacity), the time for all n pushes remains O(n)! Trupti Agrawal 42
  • 43. Queues  Linear list.  One end is called front.  Other end is called rear.  Additions are done at the rear only.  Removals are made from the front only. Trupti Agrawal 43
  • 44. Bus Stop Queue Bus Stop front rear rear rear rear rear Trupti Agrawal 44
  • 45. Bus Stop Queue Bus Stop front rear rear rear Trupti Agrawal 45
  • 46. Bus Stop Queue Bus Stop front rear rear Trupti Agrawal 46
  • 47. Bus Stop Queue Bus Stop front rear rear Trupti Agrawal 47
  • 48. Revisit Of Stack Applications  Applications in which the stack cannot be replaced with a queue.  Parentheses matching.  Towers of Hanoi.  Switchbox routing.  Method invocation and return.  Try-catch-throw implementation.  Application in which the stack may be replaced with a queue.  Rat in a maze.  Results in finding shortest path to exit. Trupti Agrawal 48
  • 49. Queue Operations  IsFullQ … return true iff queue is full  IsEmptyQ … return true iff queue is empty  AddQ … add an element at the rear of the queue  DeleteQ … delete and return the front element of the queue Trupti Agrawal 49
  • 50. Queue in an Array  Use a 1D array to represent a queue.  Suppose queue elements are stored with the front element in queue[0], the next in queue[1], and so on. Trupti Agrawal 50
  • 51. Queue in an Array(Linear Queue) a b c d e 0 1 2 3 4 5 6  DeleteQ() => delete queue[0]  O(queue size) time  AddQ(x) => if there is capacity, add at right end  O(1) time Trupti Agrawal 51
  • 52. Circular Array(Circular Queue)  Use a 1D array queue. queue[] • Circular view of array. [0] [1] [2] [3] [4] [5] Trupti Agrawal 52
  • 53. Circular Array • Possible configuration with 3 elements. [0] [1] [2] [3] [4] [5] A B C Trupti Agrawal 53
  • 54. Circular Array • Another possible configuration with 3 elements. [0] [1] [2] [3] [4] [5] B A C Trupti Agrawal 54
  • 55. Circular Array • Use integer variables front and rear. – front is one position counterclockwise from first element – rear gives position of last element [0] [1] [2] [3] [4] [5] A B C front rear [0] [1] [2] [3] [4] [5] B A C front rear Trupti Agrawal 55
  • 56. Add An Element [0] [1] [2] [3] [4] [5] A B C front rear • Move rear one clockwise. Trupti Agrawal 56
  • 57. Add An Element • Move rear one clockwise. • Then put into queue[rear]. [0] [1] [2] [3] [4] [5] A B C front D rear Trupti Agrawal 57
  • 58. Delete An Element [0] [1] [2] [3] [4] [5] A B C front rear • Move front one clockwise. Trupti Agrawal 58
  • 59. Delete An Element • Then extract from queue[front]. [0] [1] [2] [3] [4] [5] A B C front rear • Move front one clockwise. Trupti Agrawal 59
  • 60. Moving rear Clockwise • rear++; if (rear = = capacity) rear = 0; front rear [0] [1] [2] [3] [4] [5] A B C • rear = (rear + 1) % capacity; Trupti Agrawal 60
  • 61. Empty That Queue [0] [1] [2] [3] [4] [5] B A C front rear Trupti Agrawal 61
  • 62. Empty That Queue [0] [1] [2] [3] [4] [5] B C front rear Trupti Agrawal 62
  • 63. Empty That Queue [0] [1] [2] [3] [4] [5] C front rear Trupti Agrawal 63
  • 64. Empty That Queue [0] rear [1] [2] [3] [4] [5] front Trupti Agrawal 64
  • 65. Dequque  In computer science, a double-ended queue (dequeue, often abbreviated to deque) is an abstract data type that generalizes a queue, for which elements can be added to or removed from either the front (head) or back (tail).  It is also often called a head-tail linked list, Trupti Agrawal 65
  • 66. Dequque [Cont…]  This differs from the queue abstract data type or First-In- First-Out List (FIFO), where elements can only be added to one end and removed from the other. This general data class has some possible sub-types:  An input-restricted deque is one where deletion can be made from both ends, but insertion can be made at one end only.  An output-restricted deque is one where insertion can be made at both ends, but deletion can be made from one end only Trupti Agrawal 66
  • 67. Dequque [Cont…]  Both the basic and most common list types in computing, queues and stacks can be considered specializations of deques, and can be implemented using deques. Trupti Agrawal 67
  • 68. Applications of stacks: Conversion form infix to postfix and prefix expressions  There are a number of applications of stacks such as:  To print characters/string in reverse order.  Check the parentheses in the expression.  To evaluate the arithmetic expressions such as, infix, prefix and postfix. Trupti Agrawal 68
  • 69.  Arithmetic expression: An expression is defined as a number of operands or data items combined using several operators. There are basically three types of notations for an expression: 1) Infix notation 2) Prefix notation 3) Postfix notation (Main advantage of postfix and prefix notation are no need to use brackets) Trupti Agrawal 69
  • 70.  Infix notation: It is most common notation in which, the operator is written or placed in-between the two operands. For eg. The expression to add two numbers A and B is written in infix notation as:  A+ B • A and B : Operands • + : Operator  In this example, the operator is placed in-between the operands A and B. The reason why this notation is called infix. Trupti Agrawal 70
  • 71.  Prefix Notation: It is also called Polish notation, named after in the honor of the mathematician Jan Lukasiewicz, refers to the notation in which the operator is placed before the operand as: +AB  As the operator ‘+’ is placed before the operands A and B, this notation is called prefix (pre means before). Trupti Agrawal 71
  • 72.  Postfix Notation: In the postfix notation the operators are written after the operands, so it is called the postfix notation (post means after), it is also known as suffix notation or reverse polish notation. The above postfix if written in postfix notation looks like follows; AB+ Trupti Agrawal 72
  • 73.  Notation Conversions: Let us take an expression A+B*C which is given in infix notation. To evaluate this expression for values 2, 3, 5 for A, B, C respectively we must follow certain rule in order to have right result. For eg. A+B*C = 2+3*5 = 5*5 = 25!!!!!!!!  Is this the right result? No, this is because the multiplication is to be done before addition, because it has higher precedence over addition. This means that for an expression to be calculated we must have the knowledge of precedence of operators. Trupti Agrawal 73
  • 74. Operator Precedence Operator Symbol Precedence Exponential $ Highest Multiplication/Division *,/ Next highest Addition/Substraction +,- Lowest Trupti Agrawal 74