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

Lesson-9-Stack-Queue

The document discusses data structures, specifically Stacks and Queues, emphasizing their importance in maximizing efficiency in computer tasks. It details the operations, implementations, and applications of these structures, including symbol balancing and palindrome recognition. Additionally, it touches on advanced structures like deques and priority queues, highlighting their unique functionalities.

Uploaded by

daagydd
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)
2 views

Lesson-9-Stack-Queue

The document discusses data structures, specifically Stacks and Queues, emphasizing their importance in maximizing efficiency in computer tasks. It details the operations, implementations, and applications of these structures, including symbol balancing and palindrome recognition. Additionally, it touches on advanced structures like deques and priority queues, highlighting their unique functionalities.

Uploaded by

daagydd
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/ 36

Lesson 9

Stacks and Queues:

Pure Knowledge Has


Infinite Organizing Power

1
Wholeness Statement
Knowledge of data structures allows us to
pick the most appropriate data structure for
any computer task, thereby maximizing
efficiency.
Pure knowledge has infinite organizing
power, and administrate the whole universe
with minimum effort.
Stack (LIFO)
 A STACK is a LIST in which insertions and
deletions can occur relative to just one
designated position (called the top of the stack).
 When discussing a Stack, the names of add(x)
and remove() are changed to push(x) and pop();
this is to avoid confusing the LIFO and FIFO
queueing disciplines
 Applications :Used for recursive method
calls, evaluate
pop remove topexpressions,
of the stack andbacktracking
return the object)
approaches.
push insert object in the top of stack
peek view object at top of the stack without removing
it
 Stack Operations
boolean Returns true if the stack is empty; otherwise
empty() returns false
Stack : An array implementation


after pushing the element
800

Observation

5
Array Implementation of a Stack
 Designate the top of the stack to be the element
with the highest index.
 Declare an int field to hold the index of the top
element of the stack
 push operation
◦ Increment the index of the top element
◦ Store the element in the array
 pop operation
◦ Decrement the index of the top element
◦ Return the top element of the stack
 peek operation
◦ Return top element of the stack
See :ArrayStackDemo.java
Implementation of STACK

 Thestandard Java distribution comes


with a Stack class, which is a subclass
of Vector.

 Vector
is an array-based
implementation of LIST.

7
8
Class Stack
Stack<E>() constructs a new stack with elements of
type E
push(value places given value on top of stack
)
pop() removes top value from stack and returns
it;
throws EmptyStackException if stack is
empty
peek() returns top value from stack without
removing it;
Stack<Integer>
throwss EmptyStackException
= new Stack<Integer>();if stack is
s.push(42);empty
s.push(-3);
s.push(17);returns number
size() of elements
// bottom [42, -3,in 17]
stacktop
isEmpty() returns true if stack has no elements
System.out.println(s.pop()); // 17
Potential Problems
 1.A matched string is a sequence of {, }, (, ), [,
and ] characters that are properly matched.
For example, “{{()[]}}” is a matched string,
but this “{{()]}” is not, since the second { is
matched with a ]. Show how to use a stack so
that, given a string of length n, you can
determine if it is a matched string in O(n) time.
 2. Suppose you have a Stack, s, that supports
only the push(x) and pop() operations. Show
how, using only a FIFO Queue, q, you can
reverse the order of all elements in s.

10
Application of Stacks: Symbol Balancing

 A Stack can be used to verify whether all


occurrences of symbol pairs (for symbol pairs like
(), [], {}) are properly matched and occur in
the correct order.
Parentheses: “(” and “)”
 Braces: “{” and “}”
 Brackets: “[” and “]”
 Each opening symbol must match its corresponding
closing symbol. For example, a left bracket, “[,” must
match a corresponding right bracket, “],” as in the
following expression
 [(5+x)−(y+z)].
 Another e.g. is HTML Tag.
Application of Stacks: Symbol
Balancing
 1. A Stack can be used to verify whether all occurrences of
symbol pairs (for symbol pairs like (), [], {}) are properly
matched and occur in the correct order.
 2. The following procedure can be used:
 a. Begin with an empty Stack
 b. Scan the text (will ignore all non-bracketing symbols)
 c. When an open symbol is read, push it
 d. When a closed symbol is read, pop the Stack –
 i. if the stack is empty (so it can't be popped) report an error
 ii. if the popped symbol doesn't match the symbol just read,
report an error
 e. After scanning is complete, if the Stack is not empty, report
an error

12
Demo code
StackDemo.java
ArrayStackDemo.java

13
Main Point 1

Stacks are data structures that allow very


specific and orderly insertion, access, and
removal of their individual elements; only the
top element can be inserted, accessed, or
removed. Similarly, nature is orderly; an
apple seed will yield only an apple tree.
Queue (FIFO)
 Definition. Like a STACK, a QUEUE is a
specialized LIST in which insertions may
occur only at a designated position (the
rear) and deletions may occur only at a
designated position (the front).
 Applications : Used for printer queues,

queue of network data packets to send


 Queue Operations
dequeue remove the element at the front (usually also returns
this object)
enqueue insert object at the back
peek view object at front of queue without removing it

15
Real world examples of a first-in,first-out queue (a) People waiting in line to
purchase tickets (b) Phone call being routed to a customer service center

16
Queue : An array implementation


after enqueuing
(adding) the
element 800

18
Queue Implementation
 1. Using a Linked List
 a. Implementation is straightforward
 b. Good idea to use a circular Linked List to
facilitate fast enqueuing

 Using a Array
◦ Need to maintain pointers to index of front and
rear elements and need to enlarge the array
Observation

20
The Queue Operations
 Create an empty queue
◦ new object constructor call
 Determine whether the queue is empty
◦ isEmpty
 Add an item to the end of the queue
◦ enqueue
 Remove an item from the front of the
queue
◦ dequeue
 Retrieve the item at the front of the queue
◦ peek
 Remove all items from the queue
◦ removeAll
Java's Implementation
 No implementation available till j2se5.0
 In j2se5.0, an interface Queue<E>

(implemented by LinkedList<E>) is
provided, with these declared operations:
 E peek() -- returns but does not remove the

front of the queue


 void add(E obj) – same as enqueue
 E remove() – returns and removes the front

of the queue (same as dequeue)

22
Class Queue
Queue<E>() constructs a new Queue with elements of type E
add(value) place the given value at back of queue
remove() removes value from front of queue and returns it;
throws a NoSuchElementException if queue is
empty
peek() returns front value from queue without removing it;
returns null if queue is empty
size() returns number of elements in queue
isEmpty() returns q
Queue<Integer> true if queue
= new has no elements
LinkedList<Integer>();
q.add(42);
q.add(-3);
q.add(17); // front [42, -3, 17] back
System.out.println(q.remove()); // 42
◦ IMPORTANT: When constructing a queue you
must use a new LinkedList object instead of
a new Queue object.
Queue in Java
◦ provides the following operations:
1. element(): This method retrieves the head of the queue.
2. offer(): This inserts the specified element into the queue.
3. peek(): This method retrieves the head of this queue,
returning null if this queue is empty.
4. poll(): This method retrieves and removes the head of this
queue, or return null if this queue is empty.
5. enqueue(e): Adds element e to the back of queue.
6. dequeue( ): Removes and returns the first element from the
queue (or null if the queue is empty).
QueueDemo.java, LinkedQueueDemo.java
Application of the Queue
ADT
 Recognizing Palindromes
Strings that read the same from left to right as
they do from right to left
E.g., aba, abba
Algorithm for Recognizing
Palindromes
 Create an empty queue or stack
 Scan and insert characters one by one into
both the queue or stack
 Remove and compare each character from
the stack or queue
◦ If they are different at any point, then the string is
not a palindrome

Give an example – cbc, and cbc


DEQUEUES
 A deque is a double-ended queue pronounced
as ‘deck’.
 It supports insertion and deletion at both the

front and the back of the queue.


 The methods might be called insertLeft() and

insertRight(), and removeLeft() and


removeRight().
28
Contd..
 If you restrict yourself to insertLeft() and
removeLeft() (or their equivalents on the
right), then the deque acts like a stack. If
you restrict yourself to insertLeft() and
removeRight() (or the opposite pair), then it
acts like a queue.

29
Contd..
 addFirst(e): Insert a new element e at the front of the deque.
 addLast(e): Insert a new element e at the back of the deque.
 removeFirst( ): Remove and return the first element of the deque
 (or null if the deque is empty).
 removeLast( ): Remove and return the last element of the deque
 (or null if the deque is empty).
 Additionally, the deque ADT will include the following accessors:
 first( ): Returns the first element of the deque, without removing
it (or null if the deque is empty).
 last( ): Returns the last element of the deque, without removing
it
 (or null if the deque is empty).
 size( ): Returns the number of elements in the deque.
 isEmpty( ): Returns a boolean indicating whether the deque is
empty.

30
Priority Queues
 A priority queue is a more specialized data
structure than a stack or a queue.
 Similar to Queue, having front and rear.
 Items are removed from the front.
 Items are ordered by key value so that the
item with the lowest key (or highest) is
always at the front.
 Items are inserted in proper position to
maintain the order.
 Eg: Used in multitasking operating system.
Predefined Library
Queue<Integer> pq = new
PriorityQueue<Integer>();
pq.add(25);
pq.add(15);
pq.add(35);
System.out.println("Priority Queue Elements :
" + pq);
Deque<String> dq = new LinkedList();
dq.add ("Java"); //add element at tail
dq.addFirst("C#"); //add element at head
dq.addLast ("Software Engineering"); //add element
at tail
System.out.println("DQueue Elements : " +
dq); 32
Implementing Stacks and
Queues
 Use an array to implement Stack
 Use a linked list to implement Queue
 Since the insertion and deletion operations
on a stack are made only at the end of the
stack, using an array to implement a stack is
more efficient than a linked list.
 Since deletions are made at the beginning of
the list, it is more efficient to implement a
queue using a linked list than an array list.
Main Point 2
The Queue ADT is a special ADT that supports
access or removal from the front of the queue
and insertion at the end. Queues achieve
their high level of efficiency by concentrating
on a single point of insertion (end) and a
single point of removal and access (front). In
a similar way, the dynamism of creation arises
from the concentration of dynamic
intelligence at a point.
CONNECTING THE PARTS
OF KNOWLEDGE WITH
THE WHOLENESS OF
KNOWLEDGE
1. There are infinitely many ways to design large
programs.
2. With the knowledge of data structures such as
Lists, Stacks, and Queues, one can design
programs that run most efficiently and simply.
3. Transcendental Consciousness is the
unbounded field of pure awareness.
4. Wholeness moving within itself : In Unity
Consciousness, creation is seen as the
interaction of unboundedness and point value:
the unbounded collapses to its point value;
point value expands to infinity, all within the
wholeness of awareness.

You might also like