{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Lecture07 - Stacks and Queues EECS 233 Last Week Lists How...

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

View Full Document Right Arrow Icon
Stacks and Queues EECS 233
Background image of page 1

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

View Full Document Right Arrow Icon
-2- Last Week: Lists How to represent a sequence of objects? Lists Data structures: Array implementation Linked lists Operations or methods: Insert Remove Traversal etc
Background image of page 2
-3- Stack ADT A stack is a special sequence in which: items can be added and removed only at one end (the top ) you can only access the item that is currently at the top Operations: boolean push(ItemType i); add an item to the top of the stack ItemType pop(); remove the item at the top of the stack ItemType peek(); get the item at the top of the stack, but don t remove it boolean isEmpty(); boolean isFull(); The interface provides no way to access/insert/delete an item at an arbitrary position. Enforced by encapsulation push pop/peek push(8); push(15); push(9); pop() - returns 9 8 15 9
Background image of page 3

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

View Full Document Right Arrow Icon
-4- Array Implementation of Stacks Example: the integer stack would be represented as follows: items top max 2 1000 stack reference/pointer ArrayStack 8 15 9 8 15 9
Background image of page 4
-5- Array Implementation: Constructors and Methods public ArrayStack(int max) { items = new int[max]; // a stack of integers top = -1; maxSize = max; } public boolean isEmpty() { return (top == -1); } public boolean isFull() { return (top == maxSize – 1); }
Background image of page 5

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

View Full Document Right Arrow Icon
-6- Generic ArrayStack Class Generic classes use type variables T that serve as placeholders for actual types. public class ArrayStack<T> { private T[ ] items; private int top; private int maxSize; public boolean push(T item) { } Constructor is rewritten as: public ArrayStack(int max) { items = (T[ ]) new Object[max]; top = -1; maxSize = max; } Usage: ArrayStack<Bag> bagStack = new ArrayStack<Bag>(100); Methods: push(), pop(), peek() public boolean push(T item) { if (isFull()) return false; top++; items[top] = item;
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.

{[ snackBarMessage ]}