download

CPSC 131 Data Abstraction
Concepts
STACKS
7/11/2017
Lambright
CPCS 131
1
Abstract Data Type
STACK
ADT help us conceptualize problems at different
level of complexity.
In terms of ADT, Data Management requires
three things.
Identification of useful sets of operations.
There is an application that can use the ADT.
An implementation for the ADT - requires
user-defined data structure.
A Stack is a well know ADT.
7/11/2017
Lambright
CPCS 131
2
Abstract Data Type
STACK
Problem
You want to read in a line of string from the
standard input and print it in reverse order.
There is no backspace key on the terminal so
if a mistake is made during entry, the # key is
used to signify deletion.
What are some ways we might solve this
problem?
7/11/2017
Lambright
CPCS 131
3
Abstract Data Type
STACK
Let’s use the following string to illustrate the
problem. Given the following.
Abcde2#fghi1k##lmnopqrsst##tuvxyz
What is the correct string?
Abcdefghilmnopqrstuvxyz
Now what will the reverse output?
zyxvutsrqponmlihgfedcbA
Now let’s take this problem and develop an ADT.
7/11/2017
Lambright
CPCS 131
4
Abstract Data Type
STACK
List the “Whats”
First we must read the line of characters and
correct “entry errors”
Print line in reversed order.
ReadAndCorrect (s)
{Reads the input line. For each character read,
either enters it on to the stack S or, if it is #,
corrects the contents of S.
7/11/2017
Lambright
CPCS 131
5
Abstract Data Type
STACK
What is a STACK?
How can we describe the operations of a
STACK?
Let’s demonstrate with a stack of dishes.
15
10
5
7/11/2017
Lambright
CPCS 131
6
Abstract Data Type
STACK
What operations we need for stack.
CreateStack (S).
{creates and empty stack S.}
StackIsEmpty (S)
{determines whether stack S is empty}
7/11/2017
Lambright
CPCS 131
7
Abstract Data Type
STACK
StackIsFull (s)
{Determine whether stack is full}
Push (s, newItem)
{Adds NewIem to stack S.}
Pop (s)
{Removes from stack S the item that was
added most recently.}
7/11/2017
Lambright
CPCS 131
8
Abstract Data Type
STACK
ClearStack (s)
{Remove all items from stack}
StackTop (s)
{Retrieves from stack S the item that was
added most recently, leaving S
unchanged.}
7/11/2017
Lambright
CPCS 131
9
Array-Based ADT Stack
 Implementation of an Array-based ADT Stack
Unit StackOperations;
{ Basic STACK operations - Array-Based Implementation
}
{ CreateStack, StackIsEmpty, StackIsFull, Push, Pop, ClearStack,}
{ and StackTop
}
interface
const
MaxStack = 20;{<maximum size of stack>;}
type
itemType = integer;{<desired type of stack item>; }
stackType = record


7/11/2017
Top : 0..MaxStack;
Items
: array[1..MaxStack] of itemType
end; { record }
Lambright
CPCS 131
10
Array-Based ADT Stack
procedure CreateStack(var S : stackType);
{ -------------------------------------------------------Creates an empty stack.
Precondition: None.
Postcondition: The stack S is empty.
-------------------------------------------------------- }
function StackIsEmpty(S : stackType) : boolean;
{ -------------------------------------------------------Determines whether a stack is empty.
Precondition: CreateStack(S) has been called.
Postcondition: Returns true if S was empty, else returns
false.
--------------------------------------------------------}
7/11/2017
Lambright
CPCS 131
11
Array-Based ADT Stack
function StackIsFull(S : stackType) : boolean;
{ -------------------------------------------------------Determines whether a stack is Full.
Precondition: CreateStack(S) has been called.
Postcondition: Returns true if S was Full, else returns
false.
--------------------------------------------------------}
7/11/2017
Lambright
CPCS 131
12
Array-Based ADT Stack
procedure Push(var S : stackType; NewItem : itemType;
var Success : boolean);
{ -------------------------------------------------------Adds an item to the top of a stack.
Precondition: CreateStack(S) has been called.
Postcondition: If S was not full, NewItem is on the top
of the stack S and Success is true; otherwise Success is
false.
Note: S is full if it has MaxStack items.
--------------------------------------------------------
7/11/2017
Lambright
CPCS 131
}
13
Array-Based ADT Stack
procedure Pop(var S : stackType; var Success : boolean);
{ -------------------------------------------------------Removes the top of a stack.
Precondition: CreateStack(S) has been called.
Postcondition: If S was not empty, the item that was
added most recently to S is removed and Success is true.
However, if S was empty, deletion is impossible and Success
is false.
-------------------------------------------------------- }
7/11/2017
Lambright
CPCS 131
14
Array-Based ADT Stack
procedure GetStackTop(S : stackType;
var StackTop: itemType; var Success : boolean);
{ -------------------------------------------------------Retrieves the top of a stack.
Precondition: CreateStack(S) has been called.
Postcondition: If S was not empty, StackTop contains the
item that was added most recently to S and Success is
true. However, if S was empty, the operation fails and
Success is false. S is unchanged.
-------------------------------------------------------- }
7/11/2017
Lambright
CPCS 131
15
Array-Based ADT Stack
procedure ClearStack(var S : stackType);
{ -------------------------------------------------------Remove all items from the Stack.
Precondition: CreateStack(S) has been called.
Postcondition: No item on Stack S.
-------------------------------------------------------- }
7/11/2017
Lambright
CPCS 131
16
Array-Based ADT Stack
implementation
procedure CreateStack(var S : stackType);
begin
S.Top := 0
end; { CreateStack }
function StackIsEmpty(S : stackType) : boolean;
begin
StackIsEmpty := (S.Top < 1)
end; { StackIsEmpty }
7/11/2017
Lambright
CPCS 131
17
Array-Based ADT Stack
procedure Push(var S : stackType; NewItem : itemType;
var Success : boolean);
begin
Success := (S.Top < MaxStack);
if Success
then
begin
{ stack is not full }
S.Top := succ(S.Top);
S.Items[S.Top] := NewItem;
end
end; { Push }
7/11/2017
Lambright
CPCS 131
18
Array-Based ADT Stack
procedure Pop(var S : stackType; var Success : boolean);
begin
Success := not StackIsEmpty(S);
if Success
then S.Top := pred(S.Top)
end; { Pop }
7/11/2017
Lambright
CPCS 131
19
Array-Based ADT Stack
procedure GetStackTop(S : stackType;
var StackTop: itemType; var Success : boolean);
begin
Success := not StackIsEmpty(S);
if Success
then StackTop := S.Items[S.Top]
end; { GetStackTop }
7/11/2017
Lambright
CPCS 131
20
Array-Based ADT Stack
function StackIsFull(S : stackType) : boolean;
begin
StackIsEmpty := (S.Top = MaxStack)
end; { StackIsFull }
procedure ClearStack(var S : stackType);
begin
S.Top := 0;
end; {ClearStack}
end. { unit }
7/11/2017
Lambright
CPCS 131
21
Applications For ADT Stack
 Checking for Balanced Parentheses
Stacks are referred to as “Last-In-First-Out (LIFO).
Lets view two strings with parentheses. Both have
the equal numbers of left and right parent’s
abc(defg(ijk)(l(mn))op)qr
abc(def))(ghij(kl)m
 Parentheses are balanced if:
Each “)” is matched with an already encountered “(“
At end of string, we have matched each “(“
7/11/2017
Lambright
CPCS 131
22
Applications For ADT Stack
Demo Stack walk through with input string of
(a(b)c) - balanced
(a(bc) - Not balanced Stack not empty
(ab)c) - Not balanced, Stack empty with
“)”
7/11/2017
Lambright
CPCS 131
23
Recognizing Strings with
Stacks
 Lets look at Palindromes
L = { w$w’ : w is string of characters other than $,
w’ = reverse of w.
deed - de$ed,
 In this application, we push all characters on the stack
until we hit the “$”.
 After the “$” we pop all characters of the stack until we
encounter the end of string.
 If the characters after the “$” does not match the stack,
then the string in not part of the language.
 If the stack is not empty at then it is not balanced.
7/11/2017
Lambright
CPCS 131
24
Psuedo Code for Balanced
Parentheses
CreateStack (Stack)
Continue := true
I := 1
While (I <= length(Str)) and Continue do
begin
{ ignore all characters other than parentheses}
if (Str[I] <> ‘)’ ) and (Str[I] <> ‘(‘ ) then
I := succ(I)
{ push an open parenthesis }
else if Str[I] = ‘(‘ then
begin
Push (Stack, ‘(‘, Success)
I := succ(I)
7/11/2017 end
Lambright CPCS 131
25
Psuedo Code for Balanced
Parentheses
{close parenthesis: pop a matching open parenthesis }
else if not StackIsEmpty(Stack) then
begin
Pop (Stack, Success)
I := succ (I)
end
else continue := false
end {While (I <= length(Str)) and Continue}
if (I > length(str)) and StackIsEmpty (Stack)
then Stack is balanced
else Stack is not balanced
7/11/2017
Lambright
CPCS 131
26
Complex Application of
Stacks
 Stacks can be used to evaluate algebraic expression
 There are three ways to specify the syntax of algebraic
expression
Prefix, infix, and postfix
Prefix -> *2+34
Infix ->
2*3+4
Postfix -> 234+*
Some calculators (HPs) use Postfix operations
Demonstrate calculator
7/11/2017
Lambright
CPCS 131
27
Infix Notation
What are some of the problems with Infix
notation?
The term “infix” indicates that every binary
operator appears between its operands.
a+b*c
It necessitates associativity rules, precedence
rules, and the use of parentheses to avoid
ambiguity.
It is hard for the machine to interpret
without the rules
7/11/2017
Lambright
CPCS 131
28
Infix Notation
Associative rules
Given the expression a + b * c
What is the second operand of the +?
Is it b or is it (b*c)?
What is the first operand of the *?
Is it b, or is it (a + b)?
What out applying the rule the answer is
ambiguous.

7/11/2017
Lambright
CPCS 131
29
Infix Notation
 Precedence rules
Precedence rule states that certain operator has
precedence over others.
Example:
*, /, +, - (See back of text book for the list)
* and / have equal precedence; and + and - have
equal precedence
Given the expression: a/b*c
How would you interpret the expression?
Common practice is to evaluate the expression from
left to right.
7/11/2017
Lambright
CPCS 131
30
Infix Notation
 Parenthesis
In the use of Infix notation the parenthesis is used to
reduce the ambiguity of the expression.
 a/(b*c) or
 (a/b)*c
 The alternatives to infix notation is prefix and postfix.
 Prefix and postfix expressions avoid the ambiguity
inherent in the evaluation of infix expressions
 Prefix will be covered in Chapter 6.
7/11/2017
Lambright
CPCS 131
31
Postfix
 Let evaluate postfix expression to compute the value
2*(3+4)
 The postfix expression is 234+*
 The numbers are the operands and symbols are the
operators.
7/11/2017
Lambright
CPCS 131
32
PostFix Psuedocode
For each character ch in the string do
begin
if ch is an operator name Op
then
begin
{ evaluate and push the result }
Oprnd2 := StackTop (S)
Pop (S)
oprnd1 := StackTop (S)
Pop (S)
Result := Oprnd1 op Oprnd2
Push (S, Result)
end { then}
else Push (S, ch)
{ ch is an operand}
end
7/11/2017
Lambright
CPCS 131
33
Postfix Evaluation
Key entered
Calculator
Stacks
2
Push (S, 2)
2
3
Push (S, 3)
2 3
4
Push (S, 4)
2 3 4
+
Oprnd2 := Stacktop(S)
2 3 4
Pop (S)
2 3
Oprnd1 := Stacktop(S)
2 3
Pop (S)
2
Result := Oprnd2 + oprnd1
2
Push (S, Result)
2 7
7/11/2017
Lambright
CPCS 131
34
Postfix Evaluation
Key entered
Calculator
Stacks
*
Oprnd2 := Stacktop(S)
2 7
Pop (S)
2
Oprnd1 := Stacktop(S)
2
Pop (S)
Result := Oprnd2 + oprnd1
Push (S, Result)
7/11/2017
Lambright
CPCS 131
14
35
Converting From infix to
Postfix
 Key facts
The operands always stay in the same order with
respect to one another.
An operator will move only “to the right” with respect
to the operands; that is, in the infix expression, the
operand X precedes the operator Op, it is also true
that in the postfix expression the operand X precedes
the operator Op.
All parentheses are removed.
7/11/2017
Lambright
CPCS 131
36
Converting From infix to
Postfix
 When an operand is encountered, append it to the
output string PE.
 Push each “(“ onto the stack.
 When you encounter a “)”, you pop operators off the
stack, appending them to the end of PE until you
encounter the matching “(“.
7/11/2017
Lambright
CPCS 131
37
Converting From infix to
Postfix
 When you encounter an operator, if the stack is empty,
push the operator onto the stack. However, if the stack
is not empty, pop operators of greater or equal
precedence from the stack, appending theme to PE.
Stop when you encounter either a “(“ or an operator of
lower precedence or when the stack becomes empty.
Then push the new operator on the stack.
 When you reach the end of the string, you append the
remaining contents of the stack to PE.
7/11/2017
Lambright
CPCS 131
38
Infix to Postfix Psuedocode
for each character Ch in the infix expression do
case Ch of
operand : PE := PE concat Ch
‘(‘
: Push (S, Ch)
‘)’
: begin {pop down to the matching open Parent}
while StackTop (S) <> ‘(‘ do
begin
PE: := PE concat StackTop(S)
Pop (S)
end {while StackTop (S)}
7/11/2017
Lambright
CPCS 131
39
Infix to Postfix Psuedocode
(Cont’d)
Operator:
begin
while not StackIsEmpty (S)
Cand ((StackTop (S) <> ‘(‘ ) and
(Precedence (StackTop(S)) >=
Precedence (Ch))) do
begin
PE := PE concat StackTop (S)
Pop (S)
end {while not StackIsEmpty}
Push (S, Ch)
end { Operator}
7/11/2017
Lambright
CPCS 131
40
Infix to Postfix Psuedocode
(cont’d)
{append to PE the operators remaining on the stack }
while not StackIsEmpty (S) do
begin
PE := PE concat StackTop (S)
Pop (S)
end {while not StackIsEmpty}
7/11/2017
Lambright
CPCS 131
41
Infix to PostFix
A-(B+C*D)/E
Ch
Stack
PE
A
(
-(
A
A
A
B
+
-(
-(+
AB
AB
C
*
D
)
/
E
-(+
-(+*
-(+*
-/
-/
ABC
ABC
ABCD
ABCD*+
ABCD*+
ABCD*+E
ABCD*+E/-
7/11/2017
Lambright
CPCS 131
42
Progamming Assignment 2
Infix to Postfix
Due at the End of Class on 5 Oct 00.
7/11/2017
Lambright
CPCS 131
43