Unit03A - More Linear Data Structures Stacks Stacks 3A 1 2...

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

View Full Document Right Arrow Icon
1 1 More Linear Data Structures Stacks 3A 2 Stacks 3 Stack Operations public interface LIFOStack<E> { public void push(E element); // Insert element at top of stack public boolean isEmpty(); // Is the stack empty? public E pop(); // Remove element from top of stack public E peek(); // Examine element at top of stack } 4 Stacks using an array 0 1 2 3 4 5 6 7 8 9 10 11 Store the elements of the stack from top to bottom in order in the array. Which end should be the top of the stack? Why? 5 Array Implementation Fields public class ArrayStack<E> implements LIFOStack<E> { private E[] dataArray; private int top; // methods (next slides) } index of top stack element in array 6 Array Implementation public ArrayStack<E>() { dataArray = (E[])new Object[1]; top = -1; } public boolean isEmpty() { return (top == -1); } indicates an empty stack
Background image of page 1

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

View Full DocumentRight Arrow Icon
2 7 Array Implementation push public void push(E element) { if (__________________________) reallocate(); // not shown top = top + 1; dataArray[top] = element; } dataArray [++top] = element ; dataArray[top++] = element; NO: top == dataArray.length-1 8 Array Implementation pop public E pop() { if (__________________________) throw new NoSuchElementException(); E element = dataArray[top]; top = top - 1; return element; } return dataArray[top--]; return dataArray[--top]; NO: top == -1 9 Array Implementation peek public E peek() { if (__________________________) throw new NoSuchElementException(); return dataArray[top]; } top == -1 10 Stacks using a singly-linked list Store the elements of the stack from top to bottom in order in the list. Which end should be the top of the stack? Why? null head 11 Linked List Implementation Fields public class ListStack<E> implements LIFOStack<E> { private Node<E> top; // methods (next slides) } reference to node with top stack element in list 12 Linked List Implementation public ListStack<E>() { top = null; } public boolean isEmpty() { return (top == null); } indicates an empty stack
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 12/19/2009 for the course CS 121 taught by Professor Reid-miller during the Spring '09 term at Carnegie Mellon.

Page1 / 6

Unit03A - More Linear Data Structures Stacks Stacks 3A 1 2...

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

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