28
CHAPTER 6 Stacks Array Implementation

CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be

  • View
    217

  • Download
    2

Embed Size (px)

Citation preview

CHAPTER 6

Stacks

Array Implementation

2

Stacks

A stack is a linear collection whose elements are added and removed from one end

The last element to be put on the stack is the first element to be removed

A stack is LIFO – last in, first out

3

A conceptual view of a stack

4

Basic operations

Push: store a data item at the top of the stack

Pop: retrieve a data item from the top of the stack

5

Example Push Item 1 Push Item 2 Push Item 3 Pop Push Item 4 Pop Pop Pop

Item 1

Item 2Item 1

Item 3Item 2Item 1

Item 2Item 1

Item 4Item 2Item 1

6

More operations on a stack

7

Example

A procedure to replace the elements of a nonempty stack, assuming they are of type integers, with their sum

Pre: A nonempty stack with elements of type integers.

Post: s contains only one element - the sum of previously stored elements.

8

Algorithm

1. element1 S.pop()

2. while stack is not empty repeat 2.1. element2 S.pop()2.2. S.push(element1+element2)

2.3. element1 S.pop()

3. push(S,element1)

9

Stack applications

Undo operations in editors

Evaluating an arithmetic

expression using postfix notation

Converting infix expression into

postfix expression

Depth-first search in a tree/graph

10

Stack implementation

The interface class Array implementation Linked implementation

11

Generic Types

Java enables us to define a class based upon a generic type

This means that we can define a class so that it stores, operates on, and manages objects whose type is not specified until the class is instantiated

The type supplied at the time of instantiation replaces the type T wherever it is used in the declaration of the class

12

Example of Generic Types

class Box<T> { // declaration and code that manage objects // of type T } ...... Box<Integer> box1 = new Box<Integer>();

13

The Stack interface class public interface StackADT<T>{ // Adds one element to the top of this stack public void push (T element);

// Removes and returns the top element from this stack public T pop();

// Returns without removing the top element of this stack public T peek();

// Returns true if this stack contains no elements public boolean isEmpty();

// Returns the number of elements in this stack public int size();

// Returns a string representation of this stack public String toString();}

14

Array implementation Design decisions:

maintain an array of Object references the bottom of the stack is at index 0 the elements of the stack are in order and

contiguous an integer variable top stores the index of the

next available slot in the array

This approach allows the stack to grow and shrink at the higher indexes

15

Array implementation

16

Private variables

private final int DEFAULT_CAPACITY = 100;

private int top; // indicates the next open slot

private T[ ] stack;

17

Constructor

public ArrayStack() { top = 0; stack = (T [ ])(new Object[DEFAULT_CAPACITY]); }

public ArrayStack (int initialCapacity) { top = 0; stack = (T [ ])(new Object[initialCapacity]); }

18

Push

If the array is full, expand its capacity Store the element to be pushed at position ‘top’ Increment ‘top’

public void push (T element) { if (size() == stack.length) expandCapacity();

stack[top] = element; top++; }

19

Pop

If empty throw exception Decrement ‘top’ Get the contents at position ‘top’ into ‘result’ Return result

public T pop() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException(“stack”); top--; T result = stack[top]; return result; }

20

Peek

If empty throw exceptionReturn the contents of the top node

public T peek() throws EmptyCollectionException { if (isEmpty()) throw new

EmptyCollectionException(“stack”); return stack[top-1];}

21

isEmpty

if size is zero return true else return false

public boolean isEmpty() { if (top == 0) return true else return false; }

22

Size

return the size

public int size() { return top; }

23

Managing Capacity

Declare a new array with twice the size of the current array

Copy the elements of the current array into the new array

Update the reference variable stack to point to the new array

24

Managing Capacity

public void expandCapacity() { T[ ] larger = (T[ ])(new Object[stack.length *2]);

for(int index=0; index < stack.length; index++) larger[index] = stack[index];

stack = larger; }

25

Handling Exceptions

An exception is an object that defines an unusual or erroneous situation

A program can be designed to process an exception in one of three ways:

- Not handle the exception at all

- Handle the exception where it occurs

- Handle the exception at another point in the program

If an exception is not handled at all by the program, the program will produce an exception message and terminate

26

Handling Exceptions

public class EmptyCollectionException extends RuntimeException{//-----------------------------------------------------------------// Sets up this exception with an appropriate message.//---------------------------------------------------------------- public EmptyCollectionException (String collection) { super ("The " + collection + " is empty."); }}

27

Handling Exceptions – Try and Catch

To handle an exception when it is thrown, we use a try statementA try statement consists of a try block followed by one or more

catch clauses

try { // statements in the try block }catch (IOException exception) {

// statements that handle the I/O problem }

28

Analysis of Stack Operations

Because stack operations all work on one end of the collection, they are generally efficient

The push and pop operations, for both linked and array implementations, are O(1)

Likewise, the other operations are O(1) The expandArray method has complexity

O(n), where n is the number of elements in the stack