Data Structures and Algorithms: Stacks
Data Structures and Algorithms: Stacks
Data Structures and Algorithms: Stacks
Stacks
Stacks
Definition
A stack is a container of objects that are
inserted and removed according to the last-
in-first-out principle.
A stack allows access to only one data item:
the last item inserted. If you remove this
item, then you can access the next-to-last
item inserted, and so on. This is a useful
capability in many programming situations.
Stacks 2
Operations on Stack
Placing a data item on the top of the
stack is called pushing it.
Removing it from the top of the
stack is called popping it. These are
the primary stack operations.
A stack is said to be a Last-In-
First-Out (LIFO) storage
mechanism, because the last item
inserted is the first one to be
removed.
Examples
“back” in a web browser
“undo” in Text editors
Stacks 3
Pop
Procedure 7.1 : PUSH(STACK, TOP, LEN, ITEM)
This procedure pushes an ITEM onto a stack.
Stacks 4
POP
Procedure 7.2 : POP(STACK, TOP, ITEM)
This procedure deletes the top element of STACK
and assignees it to the variable ITEM.
Stacks 5
Peek
Push and pop are the two primary stack operations. However, it's
sometimes useful to be able to read the value from the top of the
stack without removing it.
Notice that you can only peek at the top item. By design, all the
other items are invisible to the stack user.
1 [ If Stack is Empty?]
If TOP = 0, than:
Print: Stack is Empty, and Return.
2 Set ITEM:= STACK[TOP]. [Assigns TOP element to ITEM.]
3 Return.
Stacks 6
Reversing a Word
For our first example of using a stack, we'll
examine a very simple task: reversing a word.
When you run the program, it asks you to type
in a word. When you press Enter, it displays
the word with the letters in reverse order.
A stack is used to reverse the letters. First the
characters are extracted one by one from the
input string and pushed onto the stack. Then
they're popped off the stack and displayed.
Because of its last-in-first-out characteristic,
the stack reverses the order of the characters.
Stacks 7
Algorithm for Reversing a Word
Procedure 7.3: REVERSWORD(INPUT, N, STACK, OUTPUT)
The Algorithm reverse a string INPUT of Length N
using a stack STACK and save the reverse
word in string OUTPUT.
Stacks 8
Java Code for Reversing a Word (1)
class Reverse
{
private String input;
Stacks 9
Java Code for Reversing a Word (2)
String output= new String("");
int k=0;
while(!stk.isEmpty())
{
output+= stk.pop();
k++;
}
return output;
}
}
//===============================
class TestReverse
{
public static void main(String args[])
{
String input = new String("abcdefg");
Reverse revString = new Reverse(input);
String output= new String(revString.doReverse());
System.out.println(output);
}
}
Stacks 10
Parsing Arithmetic Expressions
Another very important application of
stack is parsing (that is, analyzing)
arithmetic expressions like
2+3
or
2*(3+4)
or
((2+4)*7)+3*(9–5)
Stacks 11
Parsing Arithmetic Expressions
As it turns out, it's fairly difficult, at least for a computer algorithm,
to evaluate an arithmetic expression directly. It's easier for the
algorithm to use a two-step process:
1. Transform the arithmetic expression into a different format, called
postfix notation.
2. Evaluate the postfix expression.
Step 1 is a bit involved, but step 2 is easy. In any case, this two-
step approach results in a simpler algorithm than trying to parse
the arithmetic expression directly.
Of course, for a human it's easier to parse the ordinary arithmetic
expression. We'll return to the difference between the human and
computer approaches in a moment. Before we delve into the
details of steps 1 and 2, we'll introduce postfix notation.
Stacks 12
Infix Notation
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.
For Example
A+B C-D E*F G/H
In Infix Notation we must distinguish between
(A+B)*C and A+(B*C)
The order of the operators and operands in arithmetic
expression doesn't uniquely determine the order in which
the operations are to be performed but by using
parenthesis and operator-precedence level we
determine the order evaluation.
Stacks 13
Polish Notation (Prefix Notation)
Polish notation (Infix notation) named after the polish
mathematician Jan Jukasiewicz, refers to the notation
in which the operator symbol is placed before its two
operands.
For Example
+AB -CD *EF /GH
The Fundamental Property of Polish notation is that
the order in which the operations are to be performed
is completely determined bye the positions of the
operators and operands in expression. Accordingly we
never need parenthesis when writing expression in
Polish notation
Stacks 14
Reverse Polish Notation (Postfix Notation)
Stacks 15
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–
Stacks 16
How Humans Evaluate Infix
How do you translate infix to postfix?
Let's examine a slightly easier question first:
“how does a human evaluate a normal infix
expression”?
Although, this is difficult for a computer, we
humans do it fairly easily because of countless
hours in Dr.Nawaz's math class. It's not hard
for us to find the answer to 3+4+5, or 3*(4+5).
By analyzing how we do this, we can achieve
some insight into the translation of such
expressions into postfix.
Stacks 17
How Humans Evaluate Infix
Roughly speaking, when you "solve" an arithmetic
expression, you follow rules something like this:
1. You read from left to right. (At least we'll assume
this is true. Sometimes people skip ahead, but for
purposes of this discussion, you should assume
you must read methodically, starting at the left.)
2. When you've read enough to evaluate two
operands and an operator, you do the calculation
and substitute the answer for these two operands
and operator. (You may also need to solve other
pending operations on the left, as we'll see later.)
3. This process is continued—going from left to right
and evaluating when possible— until the end of the
expression.
Stacks 18
How Computer Evaluate Infix ?
Stacks 19
Evaluating a postfix expression
When you're finished, pop the stack to obtain the answer. That's all
there is to it.
This process is the computer equivalent of the human approach.
Stacks 20
Evaluation of Postfix Expression
Algorithms 7.4 This algorithm finds the VALUE of an
arithmetic expression P Written in Postfix notation using a
stack STACK to hold the operands.
Stacks 21
How Humans Translate Infix to Postfix
Stacks 22
How Humans Translate Infix to Postfix (2)
Stacks 23
Translating A+B–C into postfix
Stacks 24
Translating A+B*C to postfix
Character Read Infix Expression Postfix Expression Comments
from Parsed So Far Written So Far
Infix Expression
A A A
+ A+ A
B A+B AB
* A+B* AB 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 25
Translating A*(B+C) into postfix
Stacks 26
Saving Operators on a Stack
You'll notice in both examples demonstrated in last
slides that the order of the operators is reversed
going from infix to postfix. Because the first
operator can't be copied to the output until the
second one has been copied, the operators were
output to the postfix string in the opposite order
they were read from the infix string. A longer
example may make this clearer.
Next example shows the translation to postfix of
the infix expression A+B*(C–D). We include a
column for stack contents, which we'll explain in a
moment.
Stacks 27
Translating A+B*(C–D) to postfix
Stacks 28
Translation Rules
Let's make the rules for infix-to-postfix
translation more explicit. You read items from
the infix input string and take the actions
shown in previous slides.
These actions are described in pseudo-code,
a blend of Java and English.
In this table, the < and >= symbols refer to the
operator precedence relationship, not
numerical values. The opThis operator has
just been read from the infix input, while the
opTop operator has just been popped off the
stack.
Stacks 29
Translation rules
Item Read from Input(Infix) Action
Operand Write it to output (postfix)
Open parenthesis ( Push it on stack
Close parenthesis ) While stack not empty, repeat the following:
Pop an item,
If item is not (, write it to output
Quit loop if item is (
Operator (opThis) If stack empty,
Push opThis
Otherwise,
While stack not empty, repeat:
Pop an item,
If item is (, push it, or
If item is an operator (opTop), and
If opTop < opThis, push opTop, or
If opTop >= opThis, output opTop
Quit loop if opTop < opThis or item is (
Push opThis
Stacks 30
Translating Infix Expressions (1)
Algorithm 7.5: POLISH(Q,P)
Suppose Q is an arithmetic expression written in infix notation.
This algorithm finds the equivalent postfix expression P.
Stacks 31
Translating Infix Expressions (2)
6. If a right parenthesis is encountered, than:
(a) Repeatedly pop from STACK and add to P each
operator ( on the top of STACK ) until a left parenthesis is
encountered.
(b) Remove the left parenthesis. [Do not the left parenthesis to P.]
[End of If structure.]
[End of Step 2 loop.]
7. Exit.
Stacks 32
The End