lec12 - CSE 12 Implementing the Stack ADT Implementing...

Info iconThis preview shows pages 1–7. Sign up to view the full content.

View Full Document Right Arrow Icon
12 Implementing Stack using the Adapter pattern Alternative implementations of Stack Time costs of Stack implementations CSE 12 Implementing the Stack ADT
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Implementing Stack using List Recall that we are implementing the Stack ADT by adapting a List In doing the design, we first find a correspondence between Stack attributes and List attributes and/or methods If different correspondences are possible, we should pick one that is the most efficient If the List is implemented using an array (e.g. java.util.ArrayList), adding and removing at the tail of the List is most efficient
Background image of page 2
Map Stack Attributes to List Attributes and/or Methods Stack Attribute List Equivalent top size() – 1 size size() Don’t underestimate the importance of doing this mapping first. Planning now saves time later
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Map Stack Methods to List Methods A consequence of that attribute mapping is that a push operation results in adding to the tail of the List tail of list next position beyond tail location to “push” the new stack element size() – 1 + 1 = size() Stack operation List operation equivalent push( element ) add( size(), element ) E pop() E remove( size() - 1 ) E peek() E get( size() – 1 ) int size() int size() boolean isEmpty() boolean isEmpty()
Background image of page 4
ListStack: The UML Diagram
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
1 2 3 import java.util.ArrayList; 4 import java.util.List; 5 import java.util.EmptyStackException; 6 7 /** 8 * An implementation of the Stack interface that adapts 9 * a java.util.List 10 */ 11 public class ListStack<E> implements Stack<E> { 12 private java.util.List<E> stack; 13 // the top element of stack is stored at position 14 // s.size() - 1 in the list. 15
Background image of page 6
Image of page 7
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 18

lec12 - CSE 12 Implementing the Stack ADT Implementing...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online