Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC 205 Programming II The ADT Stack. Recap: ADT Abstract Data Type A collection of data (objects) A set of operations on that data Add Remove Retrieve.

Similar presentations


Presentation on theme: "CSC 205 Programming II The ADT Stack. Recap: ADT Abstract Data Type A collection of data (objects) A set of operations on that data Add Remove Retrieve."— Presentation transcript:

1 CSC 205 Programming II The ADT Stack

2 Recap: ADT Abstract Data Type A collection of data (objects) A set of operations on that data Add Remove Retrieve Size or emptiness A client of an ADT object just needs to know WHAT can be done about the data, with no knowledge about HOW it is implemented inside the ADT.

3 ADT Stack Stack is like a list w/ a much more restrictive access to the collection of data Ordered Linear structure Can be accessed (add/remove/retrieved) only from one side (called top) LIFO: last-in/first-out

4 Stack Operations Due to the unique way of accessing, the basic operations are named as Push: add a new item to top Pop: remove the top item Peek: get the top item without removing it from the stack pushpop peek

5 Stack Applications Reversing a word CAT  TAC Rearranging a train of railroad cars ARCCAR

6 The java.util.Stack Class boolean emptyempty() Tests if this stack is empty. Object peekpeek() Looks at the object at the top of this stack without removing it from the stack. Object poppop() Removes the object at the top of this stack and returns that object as the value of this function. Object pushpush(Object item) Pushes an item onto the top of this stack.Object int searchsearch(Object o) Returns the 1-based position where an object is on this stack.Object

7 Stack Applications Balanced parentheses Input 1 {ab(c)) Input 2 {[ X + Y*(Z + 7)]*(A + B)}

8 Stack Implementations Since stack can be seen as a special type of list, so one can expect two kinds of implementations: Array-based Use a primitive array to store items Limitation on capacity due to the fixed array length Additional effort when expending capacity Reference based A Node class is needed Easy to grow and shrink

9 Array-Based Implementation Instance variables CAPACITY : int items : Object[] numberOfItems Constructor Public methods Push, pop, peek, search popAll isEmpty, size,

10 An Expandable Stack The capacity is variable Replace CAPACITY with INIT_CAPACITY Add two methods getCapacity() ensureCapacity(int minCapacity) Increase the capacity when items is full Test the following codintion numberOfItems == items.length One way to increase the capacity is set numberOfItems = 2*numberOfItems + 1


Download ppt "CSC 205 Programming II The ADT Stack. Recap: ADT Abstract Data Type A collection of data (objects) A set of operations on that data Add Remove Retrieve."

Similar presentations


Ads by Google