The Stack - PowerPoint PPT Presentation

1 / 18
About This Presentation
Title:

The Stack

Description:

Stack can only accept Objects not primitives. COSC 1P03. Data Structures and Abstraction ... This time the list is pointed to by TOP. COSC 1P03. Data Structures ... – PowerPoint PPT presentation

Number of Views:42
Avg rating:3.0/5.0
Slides: 19
Provided by: hug276
Category:

less

Transcript and Presenter's Notes

Title: The Stack


1
The Stack
  • Research is what I'm doing when I don't know what
    I'm doing.
  • Wernher Von Braun (1912-1977)

2
Container ADTs
  • container
  • collection of objects
  • list-oriented collections
  • positional
  • access relative to position
  • e.g. list
  • keyed collections
  • have a key
  • accessed by key
  • representations
  • contiguous
  • arrays
  • linked
  • linked-structures

3
Stack
  • a list (initially empty) of items of some type to
    which items may be added (pushed) at one end
    (called the top) and from which items may be
    removed (popped) only from the same end (i.e. the
    top)
  • examples
  • cafeteria plate stacker
  • Pez candy dispenser
  • behaviour
  • example
  • LIFO ordering
  • operations
  • push pop
  • viewing
  • empty
  • error conditions
  • underflow
  • overflow

4
Character Stack ADT
  • item type?
  • say char
  • CharStack interface
  • methods
  • push
  • pop
  • top
  • empty
  • exceptions
  • NoItemException
  • NoSpaceException

5
Character Stack ADTContiguous Implementation
  • representation
  • based on variable-sized array
  • bottom is base (0th element)
  • top is end of collection (nth element)
  • implementation
  • CharStacks package
  • instance variables
  • array (elts) and count (top)
  • constructors
  • empty stack
  • methods
  • exceptions
  • defensive programming
  • insertion/deletion dont affect others ?O(1)

6
Character Stack ADTLinked Implementation
  • representation
  • top is front
  • list pointer points to top (front) node
  • implementation
  • instance variables
  • top is list pointer
  • constructor
  • empty stack
  • methods
  • exceptions
  • overflow?
  • Node wrapper class
  • Serializable
  • insert/delete at front ?O(1)

7
Postfix (RPN) Notation
  • algebraic expressions
  • infix notation
  • priority
  • parentheses
  • postfix notation aka Reverse Polish Notation
    (RPN)
  • Jan Lukasiewicz
  • no need for parentheses or operator priorities
  • operator follows operands
  • examples
  • evaluate left to right
  • hardware computation in ALU

8
Infix to Postfix Translation
  • manual process
  • insert all parentheses
  • convert each sub-expression from inside out
  • remove parentheses
  • automated process?
  • desire single left to right pass over input
  • properties
  • operands in same order
  • operator after operands
  • save operator
  • cannot output operator until see next one
  • if saved is higher priority output else save next
    operator
  • at end must output saved operators in LIFO order
  • use a stack

9
Rail Yard Algorithm
  • operands output as seen
  • operator
  • lower/equal priority than one on stack ? output
    stacked
  • higher priority than one on stack ? push
  • open parenthesis then push, and assume lowest
    priority
  • closed parenthesis then output operators on
    stack and discard open parenthesis (from stack) ,
    discard closed parenthesis
  • when done
  • emit stacked operators
  • special cases
  • no operator on stack ? push
  • have low priority operator () at bottom of stack
  • end of expression ? pop
  • have low priority operator () at end of
    expression

10
Example InfToPost
  • client of CharStack
  • translate method
  • initialization
  • create stack (ConCharStack or LnkCharStack)
  • String as char array
  • append
  • push
  • main loop
  • process 1 character from input at a time
  • operand ? output
  • operator ? output some stacked operators then
    push
  • operator priorities
  • relative
  • prio method

11
Generic ADTs
  • behaviour of stack independent of type of item
  • generalize interface to allow any item type
  • generic Stack interface
  • based on hypothetical content type E
  • generalization (abstraction) over the content
    type
  • changes from CharStack
  • change in name of exceptions
  • change from char to E throughout
  • addition of generic parameter ltEgt after interface
    name
  • E is a type variable
  • Collections package
  • set of collection ADT (stack, queue, list, )
  • common names for exceptions

12
Client Classes
  • cost of genericity
  • little added complexity in the client class
  • stacked items implement the interface of Stack
    ltEgt
  • item type as E
  • push OK
  • automatic wrapping of primitive types
  • autoboxing
  • pop returns an object
  • primitive types are unwrapped automatically
  • autounboxing
  • Linked implementation
  • define Node with a generic formal type
  • NodeltEgt is the type for Node.
  • E is the type for the element stored within
    NodeltEgt
  • Serializable, in case we want to write the stack
    to disk

13
Type Compatibility
  • implements clause declares that the
    ActualTypeParameter for Stack is whatever is
    supplied as ActualTypeParameter for ConStack
  • thus
  • ConStackltCharactergt implements StackltCharactergt
  • and
  • ConStackltStudentgt implements StackltStudentgt
  • and so in
  • StackltCharactergt opStack
  • opStack new ConStackltCharactergt() is valid
  • opStack new ConStackltStudentgt() is invalid

14
Type Checking
  • how does the compiler type check within generic
    class, e.g.
  • eltstop item
  • with ConStackltCharactergt, Character is
    substituted for E so this is OK
  • how does compiler know?
  • ActualTypeParameter must be a ReferenceType
  • all ReferenceTypes are subtypes of Object
  • compiler type checks assuming TypeVariable is
    Object
  • thus only operations available on the
    TypeVariable are those available on Object
  • note compiler can still handle the elts array
    since it knows it is an array of some reference
    type and thus each element is a reference (4
    bytes)

15
  • note that in the constructor
  • elts (E) new Objectsize
  • is used instead of the expected
  • elts new Esize
  • Java does not allow a type parameter to be used
    in an array creation expression
  • creating an array of Object and downcast it to
    E achieves the desired effect
  • enabling garbage collection
  • setting array elements to null allows the nodes
    to be garbage collected
  • the generic Node class
  • in the linked version, the Node class must be
    parametric since the type of the contents is
    unknown.
  • only nodes which wrap the same generic type can
    be put onto a list which supports a nodes of that
    type.
  • NodeltCharactergt and NodeltStudentgt are different
    types
  • creation of a new Node is done via
  • top new NodeltEgt(item,top)

16
Example InfToPostG
  • version of InfToPost using generic Stack
  • Chararacter
  • wrapper for char primitive type
  • algorithm the same
  • wrapping and unwrapping
  • automatic in Java 1.5 and up.
  • generics and templates

17
Java Collections Framework
  • Java library for data structure ADTs
  • java.util
  • stacks, queues, lists, sets, maps
  • Collection interface
  • generic in element type
  • operations common to all collections (except
    maps)
  • methods return boolean if the operation changed
    the collection (i.e. added or removed)
  • Stack class
  • generic in element type (E)
  • array implementation (Vector) grows to fit (no
    overflow)
  • some duplication of methods (legacy
    implementation)
  • push returns item pushed

18
(No Transcript)
19
(No Transcript)
20
(No Transcript)
21
(No Transcript)
22
(No Transcript)
23
(No Transcript)
24
1. Load the value of x into the ALU 2. Load the
value of y into the ALU 3. Apply the operator
sum, xy
25
(No Transcript)
26
(No Transcript)
27
Stack Creation
Stack ltsome typegt aStack Stack ltStudentgt
aStack Student aStudent aStack new
StackltStudentgt(10) aStack.push(aStudent)
aStudent aStack.pop()
28
AutoBoxing
Stack can now accept the Object.
Pointer to Character
Im an Object Character which contains the
primitive char
Im a primitive char
Stack can only accept Objects not primitives
29
AutoUn-Boxing
A Popped value from the stack is expected to be a
primitive, in ths case a char.
aChar aStack.pop()
30
Stack Example
Input 1 2 3 4 5
Output 5 4 3 2 1
5
4
3
2
1
31
Char StackInterface
package CharStacks public interface CharStack
/ This method adds an item to the stack.
Stack overflow occurs if there is no room to
add another item. _at_param item the item
(char) to be added. _at_exception NoSpaceExcepti
on no more room to add to stack./ public void
push ( char item ) / This method removes
an item to the stack. Stack underflow occurs if
there are no more items left.
_at_return char the item (char) removed.
_at_exception NoItemException no items available
in stack./ public char pop ( ) / This
method returns the top item of the stack. Stack
underflow occurs if there are no more items
left. _at_return char the top item (char).
_at_exception NoItemException no items available
in stack./ public char top ( ) / This
method returns true if the stack contains no
items. _at_return boolean whether the stack is
empty. / public boolean empty ( ) //
CharStack
The interface defines generic operations which
support a stack architecture.
32
Char Stack.
package CharStacks import java.io. public
class ConCharStack implements CharStack,
Serializable private int top // next
available element private char elts //
elements of the stack public ConCharStack
( ) this(100) // constructor public
ConCharStack ( int size ) elts new
charsize top 0 // constructor
33
Char Stack..
public void push ( char item ) if ( top gt
elts.length ) throw new OverflowException()
else eltstop item top top
1 // push public char pop ( ) if
( top lt 0 ) throw new UnderflowException()
else top top - 1 return
eltstop // pop public char top (
) if ( top lt 0 ) throw new
UnderflowException() else return
eltstop-1 // top public
boolean empty ( ) return top lt 0 //
empty // ConCharStack
34
Char Stack LinkedWrapper Class Node
package CharStacks import java.io. / This
class represents a node in the linked structure
representing the stack. / class Node
implements Serializable char item // the
item in the stack Node next // the next node
in the structure / This constructor creates
a new node for the linked structure
representing the stack. / public Node (
char i, Node n ) item i next
n // constructor // Node
35
Char Stack Linked.
package CharStacks import java.io. publ
ic class LnkCharStack implements CharStack,
Serializable private Node top // top
element of the stack / This constructor
creates a new, empty stack. / public
LnkCharStack ( ) top null //
constructor public void push ( char item )
top new Node(item,top) // push
36
Char Stack Linked..
public char pop ( ) char i if ( top
null ) throw new UnderflowException()
else i top.item top
top.next return i // pop
public char top ( ) if ( top null )
throw new UnderflowException() else
return top.item // top public
boolean empty ( ) return top
null // empty // LnkCharStack
37
Rail Yard Algorithm
((xy)3)/(z/(a-b))
38
RPN Code
/ This method returns the relative priority
of an operator. _at_param c the
operator _at_return int the relative
priority of c. / private int prio ( char c )
switch (c) case '' return
-1 case '' return 0 case '' case '-'
return 1 case '' case '/' return
2 return 0 // never executed //
prio
For operator c, determine the relative priority
and return an integer.
39
RPN Code.
private String translate ( String in )
char infix // infix string as an
array char postfix // postfix result as an
array int iPos // position of next character
in input int oPos // position of next
character in output char c // next
character in input CharStack opStack // stack
for operators infix (in
'').toCharArray() postfix new
charinfix.length-1 oPos 0 opStack new
ConCharStack(5) opStack.push('') for (
iPos0 iPosltinfix.length iPos ) c
infixiPos switch (c) case '' case
'-' case '' case '/' case '' while (
prio(opStack.top()) gt prio(c))
postfixoPos opStack.pop() oPos
oPos 1 opStack.push(c) br
eak default postfixoPos
c oPos oPos 1 return
new String(postfix) // translate
40
Generic Stack Interface
package Collections public interface Stack ltEgt
/ This method adds an item to the stack.
Stack overflow occurs if there is no room to
add another item. _at_param item the item to be
added. _at_exception NoSpaceException no more
room to add to stack. / public void push ( E
item ) / This method removes an item to
the stack. Stack underflow occurs if there
are no more items left. _at_return E the item
removed. _at_exception NoItemException no items
available in stack. / public E pop ( )
/ This method returns the top item of the
stack. Stack underflow occurs if there are
no more items left. _at_return E the top
item. _at_exception NoItemException no items
available in stack. / public E top ( )
/ This method returns true if the stack
contains no items. _at_return boolean
whether the stack is empty. / public boolean
empty ( ) // Stack
41
Generic ConStack
package Collections import java.io. public
class ConStack ltEgt implements Stack ltEgt,
Serializable private int top // next
available element private E elts //
elements of the stack / This constructor
creates a new, empty stack capable of holding
100 items. / public ConStack ( )
this(100) // constructor / This
constructor creates a new, empty stack capable of
holding a particular number of items.
_at_param size the number of items for the
stack. / public ConStack ( int size )
elts (E)new Objectsize top
0 // constructor
Important to note that the type of E is known at
this point since ConStack is an Object where the
actual type was passed when we created the new
ConStack.
42
Generic ConStack
public void push ( E item ) if ( top gt
elts.length ) throw new NoSpaceException()
else eltstop item top top
1 // push public E pop ( )
E i if ( top lt 0 ) throw new
NoItemException() else top top -
1 i eltstop eltstop
null return i // pop public E top
( ) if ( top lt 0 ) throw new
NoItemException() else return
eltstop-1 // top public
boolean empty ( ) return top lt 0 //
empty // ConStack
43
InfToPostG(Translate)
private String translate ( String in )
char infix // infix string as an
array char postfix // postfix result as
an array int iPos // position of next
character in input int oPos // position of
next character in output char c // next
character in input StackltCharactergt
opStack // stack for operators infix (in
'').toCharArray() postfix new
charinfix.length-1 oPos 0 opStack new
ConStackltCharactergt(5) opStack.push('') for
( iPos0 iPosltinfix.length iPos ) c
infixiPos switch (c) case '' case
'-' case '' case '/' case '' while (
prio(opStack.top()) gt prio(c))
postfixoPos opStack.pop() oPos
oPos 1 opStack.push(c)) b
reak default postfixoPos
c oPos oPos 1 return
new String(postfix)
Changes to InfToPost using a Generic Stack are
marked in Blue
44
Generic Node Class
package Collections import java.io. / This
class represents a node in a singly-linked list
representing a collection. _at_author D.
Hughes _at_version 1.0 (Jan.
2005) / class Node ltEgt implements
Serializable E item // the item in the
stack NodeltEgt next // the next node in the
list / This constructor creates a new node
for the singly-linked list representing a
collection. _at_param i the item in the
node. _at_param n the next node in the
list. / public Node ( E i, NodeltEgt n )
item i next n // constructor
45
The End
Write a Comment
User Comments (0)
About PowerShow.com