Presentation is loading. Please wait.

Presentation is loading. Please wait.

COSC 1P03 Data Structures and Abstraction 7.1 The Stack Research is what I'm doing when I don't know what I'm doing. Wernher Von Braun (1912-1977)

Similar presentations


Presentation on theme: "COSC 1P03 Data Structures and Abstraction 7.1 The Stack Research is what I'm doing when I don't know what I'm doing. Wernher Von Braun (1912-1977)"— Presentation transcript:

1 COSC 1P03 Data Structures and Abstraction 7.1 The Stack Research is what I'm doing when I don't know what I'm doing. Wernher Von Braun (1912-1977)

2 COSC 1P03 Data Structures and Abstraction 7.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 COSC 1P03 Data Structures and Abstraction 7.3 Stack  a list (initially empty) of items of some type to which items may be added ( push ed) at one end (called the top ) and from which items may be removed ( pop ped) 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 Pez Candy Dispenser

4 COSC 1P03 Data Structures and Abstraction 7.4 Character Stack ADT  item type?  say char  CharStack interface  methods  push  pop  top  empty  exceptions  NoItemException  NoSpaceException

5 COSC 1P03 Data Structures and Abstraction 7.5 Character Stack ADT Contiguous Implementation  representation  based on “variable-sized” array  bottom is base ( 0 th element)  top is end of collection ( n th element)  implementation  CharStacks package  instance variables  array ( elts ) and count ( top )  constructors  empty stack  methods  exceptions  defensive programming  insertion/deletion don’t affect others  O(1)

6 COSC 1P03 Data Structures and Abstraction 7.6 Character Stack ADT Linked 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 COSC 1P03 Data Structures and Abstraction 7.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 COSC 1P03 Data Structures and Abstraction 7.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 COSC 1P03 Data Structures and Abstraction 7.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 COSC 1P03 Data Structures and Abstraction 7.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 COSC 1P03 Data Structures and Abstraction 7.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 after interface name  E is a type variable  Collections package  set of collection ADT (stack, queue, list, …)  common names for exceptions

12 COSC 1P03 Data Structures and Abstraction 7.12 Client Classes  cost of genericity  little added complexity in the client class  stacked items implement the interface of Stack  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  Node is the type for Node.  E is the type for the element stored within Node  Serializable, in case we want to write the stack to disk

13 COSC 1P03 Data Structures and Abstraction 7.13 Type Compatibility  implements clause declares that the ActualTypeParameter for Stack is whatever is supplied as ActualTypeParameter for ConStack  thus ConStack implements Stack and ConStack implements Stack  and so in Stack opStack; opStack = new ConStack (); is valid opStack = new ConStack (); is invalid

14 COSC 1P03 Data Structures and Abstraction 7.14 Type Checking  how does the compiler type check within generic class, e.g. elts[top] = item;  with ConStack, Character is substituted for E so this is OK  how does compiler know?  ActualTypeParameter must be a ReferenceType  all ReferenceType s 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 COSC 1P03 Data Structures and Abstraction 7.15  note that in the constructor: elts = (E[]) new Object[size]; is used instead of the expected elts = new E[size];  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.  Node and Node are different types  creation of a new Node is done via top = new Node (item,top);

16 COSC 1P03 Data Structures and Abstraction 7.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 COSC 1P03 Data Structures and Abstraction 7.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

19

20

21

22

23

24 1. Load the value of x into the ALU 2. Load the value of y into the ALU 3. Apply the operator sum, x+y

25

26

27 Stack aStack; StudentaStudent; : aStack = new Stack (10); : aStack.push(aStudent); aStudent = aStack.pop(); Stack Creation

28 COSC 1P03 Data Structures and Abstraction 7.28 AutoBoxing I’m a primitive char I’m an Object Character which contains the primitive char Pointer to Character Stack can now accept the Object. Stack can only accept Objects not primitives

29 COSC 1P03 Data Structures and Abstraction 7.29 AutoUn-Boxing A Popped value from the stack is expected to be a primitive, in ths case a char. aChar = aStack.pop(); I’m a primitive char I’m an Object Character which contains the primitive char Pointer to Character I’m a primitive char aChar

30 COSC 1P03 Data Structures and Abstraction 7.30 Stack Example Input: 1 2 3 4 5Output: 5 4 3 2 1 1 2 3 4 5

31 COSC 1P03 Data Structures and Abstraction 7.31 Char Stack Interface 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. **@paramitemthe item (char) to be added. **@exceptionNoSpaceExceptionno 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. **@returncharthe item (char) removed. **@exceptionNoItemExceptionno 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. **@returncharthe top item (char). **@exceptionNoItemExceptionno items available in stack.*/ public char top ( ); /** This method returns true if the stack contains no items. **@returnboolean whether the stack is empty.*/ public boolean empty ( ); } // CharStack The interface defines generic operations which support a stack architecture.

32 COSC 1P03 Data Structures and Abstraction 7.32 Char Stack. package CharStacks; import java.io.*; public class ConCharStack implements CharStack, Serializable { private inttop;// next available element private char[]elts;// elements of the stack public ConCharStack ( ) { this(100); };// constructor public ConCharStack ( int size ) { elts = new char[size]; top = 0; };// constructor Supported by the CharStacks Package Array holds the stack Data Structure Top always indexes the TOP element of the stack Default constructor uses chaining to create a stack that hold 100 elements Creation of the array Initial state of a Stack is empty, so TOP indexes the first element, i.e. 0

33 COSC 1P03 Data Structures and Abstraction 7.33 Char Stack.. public void push ( char item ) { if ( top >= elts.length ) { throw new OverflowException(); } else { elts[top] = item; top = top + 1; }; };// push public char pop ( ) { if ( top <= 0 ) { throw new UnderflowException(); } else { top = top - 1; return elts[top]; }; };// pop public char top ( ) { if ( top <= 0 ) { throw new UnderflowException(); } else { return elts[top-1]; }; };// top public boolean empty ( ) { return top <= 0; };// empty }// ConCharStack Must check if the array has room for one more element, If not then raise an exception The item is placed into the array indexed by TOP Top is incremented by 1, indexing the next available slot Must check to see if there is anything to remove, if not then raise an underflow exception The TOP indexes the next available slot, so we decrement first to index the element Return the element at TOP Must check if there is a valid element present If there is, then return the element, but leave it on the stack, Note, TOP is not modified. Boolean check, if TOP is 0 then no elements, thus empty is true

34 COSC 1P03 Data Structures and Abstraction 7.34 Char Stack Linked Wrapper Class Node package CharStacks; import java.io.*; /**This class represents a node in the linked structure representing **the stack. **/ class Node implements Serializable { charitem;// the item in the stack Nodenext;// 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 Wrapper class, Node consists of Data (item) and a next pointer. Constructor accepts the data which is a char and a link to where ‘this’ node is to point. Node’s instance variables are initialized on Node creation

35 COSC 1P03 Data Structures and Abstraction 7.35 Char Stack Linked. package CharStacks; import java.io.*; public class LnkCharStack implements CharStack, Serializable { private Nodetop;// 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 Top is now represented by a pointer. A new stack is empty, so TOP will be null. Push is the same as an insert at front. This time the list is pointed to by TOP.

36 COSC 1P03 Data Structures and Abstraction 7.36 Char Stack Linked.. public char pop ( ) { chari; 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 Pop must ensure there is an item to remove, A null TOP means an empty list, thus no item to remove, An exception is raised Extract the item from the node. Top moves down the list 1 node, Note this is the same as remove from front. The data item is returned. Top must still check if there is valid data at the TOP, raise exception otherwise. If there is an item in the stack then return it, but leave it on the stack (in the list). Empty is the case when TOP is null, or empty list.

37 COSC 1P03 Data Structures and Abstraction 7.37 Rail Yard Algorithm ((x+y)*3)/(z/(a-b)) ( ( x + y+ * 3 * / ( z / ( a - b - / /

38 COSC 1P03 Data Structures and Abstraction 7.38 RPN Code /**This method returns the relative priority of ** an operator. ** **@paramcthe operator ** **@returnintthe 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 COSC 1P03 Data Structures and Abstraction 7.39 RPN Code. private String translate ( String in ) { charinfix[];// infix string as an array charpostfix[];// postfix result as an array intiPos;// position of next character in input intoPos;// position of next character in output charc;// next character in input CharStackopStack;// stack for operators infix = (in + '#').toCharArray(); postfix = new char[infix.length-1]; oPos = 0; opStack = new ConCharStack(5); opStack.push('$'); for ( iPos=0 ; iPos= prio(c)) { postfix[oPos] = opStack.pop(); oPos = oPos + 1; }; opStack.push(c); break; default : postfix[oPos] = c; oPos = oPos + 1; }; return new String(postfix); };// translate Index to the output array. Create the stack and push $, This acts as a sentinel value within the stack. For each character in the input, extract one at a time, i.e. represented by c. Determine if c is an operator or not, if operand then move it to the output array postfix[oPos]. While the current operator has a lower or equal precedence then the stacked operator, pop and output. Convert the output char array to a string and return. Output is defined as a char array Append the # terminator to the input string, convert to char array, easier to process.

40 COSC 1P03 Data Structures and Abstraction 7.40 Generic Stack Interface package Collections; public interface Stack { /**This method adds an item to the stack. Stack overflow occurs if there **is no room to add another item. **@paramitemthe item to be added. **@exceptionNoSpaceExceptionno 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. **@returnEthe item removed. **@exceptionNoItemExceptionno 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. **@returnEthe top item. **@exceptionNoItemExceptionno items available in stack.*/ public E top ( ); /** This method returns true if the stack contains no items. ** **@returnboolean whether the stack is empty.*/ public boolean empty ( ); }// Stack Defines a generic type parameter We don’t know the type of item, so it is represented as a generic type Pop and Top both return types which must be represented as generic

41 COSC 1P03 Data Structures and Abstraction 7.41 Generic ConStack package Collections; import java.io.*; public class ConStack implements Stack, Serializable { private inttop;// 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. ** **@paramsize the number of items for the stack.*/ public ConStack ( int size ) { elts = (E[])new Object[size]; top = 0; };// constructor Part of Collections. Implement a class called Stack of some generic type E. ConStack is the implementation with the same type E which implements a Stack. “elts” thus defines an array of E, which are nothing more then objects (generic). When creating the array we are creating a set of pointers which will be of type E. Note: generics must be objects. So, elts now will be constrained to containing only elements of type E. 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 COSC 1P03 Data Structures and Abstraction 7.42 Generic ConStack public void push ( E item ) { if ( top >= elts.length ) { throw new NoSpaceException(); } else { elts[top] = item; top = top + 1; }; };// push public E pop ( ) { Ei; if ( top <= 0 ) { throw new NoItemException(); } else { top = top - 1; i = elts[top]; elts[top] = null; return i; } };// pop public E top ( ) { if ( top <= 0 ) { throw new NoItemException(); } else { return elts[top-1]; } };// top public boolean empty ( ) { return top <= 0; };// empty }// ConStack “item” is of type E and is thus type compatible to elts. Pop returns an element of type E Anywhere the element type would be used, E is used. Since only objects are now placed on the stack, we can reclaim the memory used by elts[top] by setting this value to null.

43 COSC 1P03 Data Structures and Abstraction 7.43 InfToPostG (Translate) private String translate ( String in ) { charinfix[];// infix string as an array charpostfix[];// postfix result as an array intiPos;// position of next character in input intoPos;// position of next character in output charc;// next character in input Stack opStack;// stack for operators infix = (in + '#').toCharArray(); postfix = new char[infix.length-1]; oPos = 0; opStack = new ConStack (5); opStack.push('$'); for ( iPos=0 ; iPos= prio(c)) { postfix[oPos] = opStack.pop(); oPos = oPos + 1; }; opStack.push(c)); break; default : postfix[oPos] = c; oPos = oPos + 1; }; return new String(postfix); Changes to InfToPost using a Generic Stack are marked in Blue

44 COSC 1P03 Data Structures and Abstraction 7.44 Generic Node Class package Collections; import java.io.*; /**This class represents a node in a singly-linked list representing a **collection. ** **@authorD. Hughes ** **@version1.0 (Jan. 2005)*/ class Node implements Serializable { Eitem;// the item in the stack Node next;// the next node in the list /**This constructor creates a new node for the singly-linked list **representing a collection. ** **@paramithe item in the node. **@paramnthe next node in the list.*/ public Node ( E i, Node n ) { item = i; next = n; };// constructor Part of the Collections package Node is the type, Part of this type is generic “next” must thus specify the Node as the full type of the node. Same principle applies to n. n is a pointer to a Node “item” is an element of type E.

45 COSC 1P03 Data Structures and Abstraction 7.45 The End


Download ppt "COSC 1P03 Data Structures and Abstraction 7.1 The Stack Research is what I'm doing when I don't know what I'm doing. Wernher Von Braun (1912-1977)"

Similar presentations


Ads by Google