0% found this document useful (0 votes)
57 views47 pages

STACKS

- A stack is a data structure that follows the LIFO (last-in, first-out) principle. Elements added last are the first to be removed. - Common stack operations include push, which adds an element to the top of the stack, pop, which removes an element from the top, and peek, which returns the top element without removing it. - Stacks can be implemented using arrays or linked lists. Array implementations are efficient but have fixed sizes, while linked lists are more flexible in size but less efficient.

Uploaded by

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

STACKS

- A stack is a data structure that follows the LIFO (last-in, first-out) principle. Elements added last are the first to be removed. - Common stack operations include push, which adds an element to the top of the stack, pop, which removes an element from the top, and peek, which returns the top element without removing it. - Stacks can be implemented using arrays or linked lists. Array implementations are efficient but have fixed sizes, while linked lists are more flexible in size but less efficient.

Uploaded by

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

STACKS

Reading ref :
LN 2.3.1, LN 2.2.1, ULR 2.3.3
STACKS
• Everyday examples

• Stack of newspaper, stack of plates


• Can be described also as a LIFO queue
• A stack like a list or array but access
restricted only at one end
• Pictured usually vertically with access only
from the top
• A stack can be defined as a heap of
arranged data items that can be accessed
from one end only.
• New elements or nodes as they are often
called, can be added to a stack and
removed from a stack only from end. For
this reason or a main characteristic of
stack is LIFO structure (Last-In First-Out).
STACKS
• Stacks are LIFO
TOP
D
C
B
A
STACKS
• A stack is also known as a last in first out
queue (LIFO) it guarantees that the
element at the top of stack is the one that
has been on the stack for the least amount
of time.
STACK
Operations
• Push -> adding a item to the top of stack
• Pop -> remove an item from the top of the
stack
• Size -> number of elements on the stack
• IsEmpty -> checks whether stack is empty
• Clear -> deletes/remove all elements from
the stack
• Peek -> looks what is at the top of the stack
and returns without doing anything
STACK
TOP
D
PUSH

TOP
C C
B B
A A

Pushing a value adds it to the top of the stack.


STACK

POP

TOP
C
TOP
B B
A A

Popping a value removes it from the


STACKS
• Array Implementation

• List Implementation

• Ask class where would the start and end


for each implementation (i.e. looking at
efficiency)
STACKS
• A stack can be implemented either using an
array as the underlying data structure or a list.
• An array implementation of a stack is simple and
efficient but it has a fixed upper bound on the
size of the stack.
• Setting it too high could waste memory, the
converse would generate an exception if one
attempts to push on a full stack , this
unfortunately makes it not ideal.
Interface
• What is an Interface ?
• the steering wheel on a car the clutch , brake and accelerator
are the interface between you and the engine to start the car
moving
• the buttons on the front of your television set, for example, are
the interface between you and the electrical wiring on the
other side of its plastic casing. You press the "power" button
to turn the television on and off.
• a remote control is an interface between you and a television
• English language is an interface between two people,
Interface
• The protocol of behavior enforced in the military
is the interface between people of different ranks
• In programming terms and in its most common
form, an interface is a group of related methods
with empty bodies.
• As you've already learned, objects define their
interaction with the outside world through the
methods that they expose. Methods form the
object's interface with the outside world
Interface
• Similarly, a Java interface is a device that
unrelated objects use to interact with one
another.
• Java interfaces are probably most
analogous to protocols (an agreed-upon
behavior). In fact, other object-oriented
languages have the functionality of Java's
interfaces, but they call their interfaces
protocols or APIs
STACKS
Stack Interface/Java
implementation
package com.wrox.algorithms.stacks;
import com.wrox.algorithms.queues.Queue;

public interface Stack extends Queue {


public void push(Object value);
public Object pop() throws EmptyStackException;
public Object peek() throws EmptyStackException;
public void clear();
public int size();
public boolean isEmpty();
Public void createStack()
}
STACKS
UNIT TEST
• Test cases should be defined for each of
the methods in the stack interface to
ensure the correct operation of the stack
• The push(), pop(), peek(), and clear()
methods would all have unit tests
• The size(), isEmpty() methods have no
explicit tests of their own because they are
tested as part of the others
• How do you create an instance of Stack?
How do you add a new element to a
stack?
• How do you remove an element from a
stack? How do you find the size of a
stack?
STACKS
Applications
• For backtracking ,reversing
• Screen Flow management (back and
forward buttons in a browser) web site
addresses visited are saved on a stack.
• Undo /Redo function in word for example
• Parsing in programming languages
(checking for matching brackets)
• Implement a MRU cache (most recently
used) in memory management
STACKS
• Implementing a stack using an array of a
given size, N.
• Below are the Algorithms for the
Interface/API showing the ease and
simplicity of use
STACKS
Run time output (show this)
Operation Output Stack Contents
push(5) - (5)
push(3) - (5, 3)
pop() 3 (5)
push(7) - (5, 7)
pop() 7 (5)
top() 5 (5)
pop() 5 ()
pop() "error“ ()
isEmpty() true ()
push(9) - (9)
push(7) - (9, 7)
push(3) - (9, 7, 3)
push(5) - (9, 7, 3, 5)
size() 4 (9, 7, 3, 5)
pop() 5 (9, 7, 3)
push(8) - (9, 7, 3, 8)
pop() 8 (9, 7, 3)
pop() 3 (9, 7)
STACKS
Efficiency/Complexity
• Items can be both pushed and popped
from most implementations of a stack
constant O(1) time.
• That is,the time is not dependent on how
many items are in the stack and is
therefore very quick.
• No comparisons or moves are necessary.
STACKS
Efficiency/Complexity
• What do you expect the run times for the
following to be for an array implementation and
for a list implementation ?
• Method Time
• Size
• is Empty
• top
• push
• pop
STACKS
Application as a solution in code
• Reversing an array
• Push all the elements of the array in order
onto a stack then fill the array back up
again by popping the elements off the
stack
STACKS
Application as a solution in code
STACKS
Matching Parentheses
Arithmetic expressions can contain various pairs of
grouping symbols, such as
• Parentheses: "(" and ")"
• Braces: "{" and "}"
• Brackets: "[" and "]"
• Floor function symbols: " " and " "
• Ceiling function symbols: " " and " ,“
Each opening symbol must match closing symbol
[(5 + x) _ (y + z)].
STACKS
Matching Parentheses
• The following examples further illustrate
this concept:
• Correct: ( )(( )){([( )])}
• Correct: ((( )(( )){([( )])}))
• Incorrect: )(( )){([( )])}
• Incorrect: ({[])}
• Incorrect: (.
STACKS
Matching Parentheses
• c[d] // correct
• a{b[c]d}e // correct
• a{b(c]d}e // not correct; ] doesn’t match (
• a[b{c}d]e} // not correct; nothing matches
final }
• a{b(c) // not correct; nothing matches
opening {
STACK
a{b(c[d]e)f}
Character Read Stack Contents
a
{ {
b {
( {(
c {(
[ {([
d {([
] {(
e {(
) {
f {
}
STACKS
Summary
• The stack is conceptually easier to use.
• Most CPUs, and therefore most programming
languages, including Java, are stack-based.
• Stacks and Queues and data structures usually
used to simplify certain programming operations.
• In these data structures, only one data item can
be accessed.
• Stacks always add and remove from the top—
thus, they are often referred to as LIFO queues
STACKS
Summary
.
• A stack allows access to the last item inserted.
• The important stack operations are pushing
(inserting) an item onto the top of the stack and
popping (removing) the item that’s on the top.
• A stack can be implemented with arrays as the
underlying structure or with linked list.
• Stacks can easily be implemented on top of a
list or an array data structure without
constraining the implementation
STACKS
Parsing Arithmetic Expressions
• Ordinary arithmetic expressions are written in
infix notation, so-called because the operator is
written between the two operands.
• In postfix notation, the operator follows the two
operands.
• Arithmetic expressions are typically evaluated by
translating them to postfix notation and then
evaluating the postfix expression.
• A stack is a useful tool both for translating an
infix to a postfix expression and for evaluating a
postfix expression.
STACKS
Parsing Arithmetic Expressions
• Parsing is quite an important application it
means analayzing like :
• as 2+3 or
• 2*(3+4) or
• ((2+4)*7)+3*(9–5)
STACKS
Parsing Arithmetic Expressions
• Everyday arithmetic expressions are
written with an operator (+, –, *, or /)
placed between two operands (numbers,
or symbols that stand for numbers). This is
called
• infix notation because the operator is
written inside the operands. Thus, we say
2+2 and 4⁄7, or, using letters to stand for
numbers, A+B and A⁄B.
STACKS
Parsing Arithmetic Expressions
• + - have same precedence
• 3 + 4 -5
• This can be done left to right or right to left
• * is higher precedence than +.
• 3+4 * 5 4*5 = 20 + 3 = 23
• both * and / have a higher precedence than +
and –, so all multiplications and divisions must
be carried out before any additions or
subtractions (unless parentheses dictate
otherwise;
STACKS (go through)
Parsing Arithmetic Expressions
• Parentheses are used to override the normal precedence of operators

• 3*(4+5).
• Item Read Expression Parsed So Far Comments

3 3
* 3*
( 3*(
4 3*(4 You can’t evaluate 3*4
because of the parenthesis.
+ 3*(4+
5 3*(4+5 You can’t evaluate 4+5 yet.
) 3*(4+5) When you see the )you can evaluate 4+5.
3*9 After you’ve evaluated 4+5, you can
evaluate 3*9.
27
End Nothing left to evaluate.
STACKS
Parsing Arithmetic Expressions
• To translate infix to postfix notation, you follow a
similar set of rules to those for evaluating infix.
However, there are a few small changes.
• You don’t do any arithmetic.
• The idea is not to evaluate the infix expression,
but to rearrange the operators and operands into
a different format: postfix notation.
• The resulting postfix expression will be
evaluated later.
Translating A+B*C to Postfix

Character Infix Postfix Comments


Read from Expression Expression
Infix Parsed So Written So
Expression Far Far
A A A
+ A+ A
B A+B AB
* A+B* AB You can’t copy the +
because * is higher
precedence than +.
C A+B*C ABC When you see the C,
you can copy the *.
A+B*C ABC*
End A+B*C ABC*+ When you see the
end of the expression,
you can copy the +.
STACKS
Parsing Arithmetic Expressions
• Humans evaluate from left to right but for a computer it is not that easy
• TABLE 4.8 Translating A*(B+C) into Postfix
• Character Infix Postfix Comments
• Read from Expression Expression
• Infix Parsed so Written So
• Expression Far Far
• A A A
• * A* A
• ( A*( A
• B A*(B AB You can’t copy *
because of the parenthesis.
• + A*(B+ AB
• C A*(B+C ABC You can’t copy the + yet.
• ) A*(B+C) ABC+ When you see the ), you can copy
the +
• A*(B+C) ABC+* After you’ve copied the +, you can
copy the *.
• End A*(B+C) ABC+* Nothing left to copy.
STACKS
Parsing Arithmetic Expressions
• You can’t write an operator to the output
(postfix) string if it’s followed by
• a higher-precedence operator or a left
parenthesis.
• If it is, the higher-precedence operator or
the operator in parentheses must be
written to the postfix before the lower-
priority operator.
STACKS
Parsing Arithmetic Expressions
• In postfix notation (which is also called
Reverse Polish Notation, or RPN, because
it was invented by a Polish
mathematician), the operator follows the
two operands.
• Thus, A+B becomes AB+, and A⁄B
becomes AB/. More complex infix
expressions can likewise be translated into
postfix notation, as shown in next slide
STACKS
Parsing Arithmetic Expressions
TABLE 4.2 Infix and Postfix Expressions
Infix Postfix
• A+B–C AB+C–
• A*B/C AB*C/
• A+B*C ABC*+
• A*B+C AB*C+
• A*(B+C) ABC+*
• A*B+C*D AB*CD*+
• (A+B)*(C–D) AB+CD–*
• ((A+B)*C)–D AB+C*D–
• A+B*(C–D/(E+F)) ABCDEF+/–*+
Expression Scan Action operandStack operatorStack

(1 + 2) * 4 - 3 ( Phase 1.4 (

(1 + 2) * 4 - 3 1 Phase 1.1 1 (

(1 + 2) * 4 - 3 + Phase 1.2 1 (+

(1 + 2) * 4 - 3 2 Phase 1.1 12 1(+

(1 + 2) * 4 - 3 ) Phase 1.5 3

(1 + 2) * 4 - 3 * Phase 1.3 3*

(1 + 2) * 4 - 3 4 Phase 1.1 4 3*

(1 + 2) * 4 - 3 - Phase 1.2 12 –

(1 + 2) * 4 - 3 3 Phase 1.1 3 12 –

(1 + 2) * 4 - 3 none Phase 2 9
STACKS
Parsing Arithmetic Expressions
TABLE 4.9 Translating A+B*(C–D) to Postfix
Character Infix Postfix Stack
Read from Expression Expression Contents
Infix Parsed So Written So
Expression Far Far
A A A
+ A+ A +
B A+B AB +
* A+B* AB +*
( A+B*( AB +*(
C A+B*(C ABC +*(
– A+B*(C– ABC +*(–
D A+B*(C–D ABCD +*(–
) A+B*(C–D) ABCD– +*(
A+B*(C–D) ABCD– +*(
A+B*(C–D) ABCD– +*
A+B*(C–D) ABCD–* +
A+B*(C–D) ABCD–*+
Infix to Postfix Algorithm to convert
to code
• Scan the Infix string from left to right.
• Initialise an empty stack.
• If the scanned character is an Operand, add it to the Postfix string.
• If the scanned character is an Operator and if the stack is empty
Push the character to stack.
• If the scanned character is an Operand and the stack is not empty,
compare the precedence of the character with the element on
top of the stack (topStack).
– If topStack has higher precedence over the scanned character
Pop the stack
– else Push the scanned character to stack. Repeat this step as
long as stack is not empty and topStack has precedence over
the character.
Infix to Postfix Algorithm to
convert to code
• Repeat this step till all the characters are scanned.
• (After all characters are scanned, we have to add any character that
the stack may have to the Postfix string.) If stack is not empty add
topStack to Postfix string and Pop the stack. Repeat this step as
long as stack is not empty.
• Return the Postfix string.
• After the lab you should also be able to
write a small stack application program.
• To be come competent in writing
programs, you need to write a lot of
programs.
• Do it honestly so that the success is your
very own

You might also like