Docsity

Understanding Stacks: LIFO Data Structure and Implementations, Study notes of Data Structures and Algorithms

Toggle sidebar
bg1
4/5/09!
1!
H - 1!
A Stack as an Abstract Data Type!
• A stack
– Last-in, first-out (LIFO) property
• The last item placed on the stack
will be the first item removed
– Analogy
• A stack of dishes in a cafeteria
• vs: A queue
– First in, first out (FIFO) property
• The first item added is the first
item to be removed!
Stack of cafeteria dishes
(vertical slice view)
H - 2!
15.1 – Stacks!
1-2!
Top of stack
Adding an
element
Removing
an element
H - 3!
Developing the Stack ADT
• ADT stack operations
– Create an empty stack
– Determine whether a stack is empty
– Add a new item to the stack
– Remove from the stack the item that was
added most recently
– Retrieve (but not remove) from the stack
the item that was added most recently!
H - 4!
public interface StackInterface<E>!
/** Determines whether stack is empty.!
*/!
public boolean isEmpty();!
/** Adds an item to the top of a stack.!
*/!
public void push(E newItem);!
/** Removes the top of a stack.!
* Exception: Throws StackException if the stack is empty. */!
public E pop() throws StackException;!
/** Retrieves the top of a stack.!
* Exception: Throws StackException if the stack is empty. */ !
public E peek() throws StackException;!
}!
{!
pf3
pf4
pf5

Partial preview of the text

Download Understanding Stacks: LIFO Data Structure and Implementations and more Study notes Data Structures and Algorithms in PDF only on Docsity!

H - 1

A Stack as an Abstract Data Type

  • A stack
    • Last-in, first-out ( LIFO ) property
      • The last item placed on the stack

will be the first item removed

  • Analogy
    • A stack of dishes in a cafeteria
  • vs: A queue
  • First in, first out ( FIFO ) property
  • The first item added is the first

item to be removed

Stack of cafeteria dishes

(vertical slice view)

H - 2

15.1 – Stacks

1-

Top of stack

Adding an

element

Removing

an element

H - 3

Developing the Stack ADT

  • ADT stack operations
    • Create an empty stack
    • Determine whether a stack is empty
    • Add a new item to the stack
    • Remove from the stack the item that was added most recently
    • Retrieve (but not remove) from the stack the item that was added most recently H - 4

public interface StackInterface

/** Determines whether stack is empty.

public boolean isEmpty();

/** Adds an item to the top of a stack.

public void push(E newItem);

/** Removes the top of a stack.

* Exception: Throws StackException if the stack is empty. */

public E pop() throws StackException;

/** Retrieves the top of a stack.

* Exception: Throws StackException if the stack is empty. */

public E peek() throws StackException;

H - 5

Simple Example

import java.util.*; // For Java’s Stack class

public class StackTest {

public static void main (String[] args) {

Stack stk = new Stack();

stk.push("one");

stk.push("two");

stk.pop();

stk.push("three");

System.out.println("Contents of Stack using

toString(): " + stk);

  • What does stk contain?
  • How would we define toString()? (^) H - 6

Printing a Stack without destroying it!

/* returns a String representation of the contents of a Stack

from top to bottom, assuming that the E on the Stack have the

toString() method */

public String toString (Stack stk) {

/* returns a String representation of the contents of a Stack

from top to bottom, assuming that the E on the Stack have the

toString() method */

public String toString (Stack stk) {

// Create a temporary stack to hold contents of stk

Stack tempStack = new Stack();

String S =”[“;

while (!stk.empty()) {

E element = stk.pop();

S = S + element.toString() + " “;

tempStack.push(element);

S = S + “]”;

// restore contents of stk

while (!tempStack.empty())

stk.push(tempStack.pop());

return S;

H - 7 Advanced Example: Checking for Balanced Braces

An example of balanced braces

a{b{c}{d{e}}f}g

Examples of unbalanced braces

a{b}} :Too many closing braces

{c{d}e :Too few closing braces

{f(g)h] :Mismatching braces

H - 8

Checking Balanced Braces: Helper Methods

/* returns true if c is an open bracket */

public static boolean open_bracket (char c) {

return (c == '(') || (c == '{') || (c == '[') || (c == '<');

/* returns true if c is a close bracket */

public static boolean close_bracket (char c) {

return (c == ')') || (c == '}') || (c == ']') || (c == '>');

/* returns the closing bracket matching the input open bracket */

public static char matching_bracket (char c) {

if (c == '(') return ')';

else if (c == '{') return '}';

else if (c == '[') return ']';

else return '>';

H - 13

public interface StackInterface

/ Determines whether stack is empty.

    • PreconditionPostcondition: None.: Returns true if the stack is empty; otherwise returns false. / public boolean isEmpty(); /* Adds an item to the top of a stack.
    • PreconditionPostcondition:** (^) : If insertion isnewItem is the item to be added. successful, newItem is on top of the stack./ public void push(E newItem); /* Removes the top of a stack. * Precondition: None.
  • Postcondition: If the stack is not empty, the item that was added most
  • recently is removed from the stack and returned.
  • Exception: Throws StackException if the stack is empty. / public E pop() throws StackException; /* Retrieves the top of a stack.
  • Precondition: None.
    • Postconditionrecently is returned. The stack is: If the stack is not empty, the unchanged. item that was added most
  • Exception: Throws StackException if the stack is empty. / public E peek() throws StackException;*

H - 14

StackException

  • StackException
    • Any Java method that implements a stack-using algorithm should do one of the following - Take precautions to avoid an exception - Provide try and catch blocks to handle a possible

exception

/******* file StackException.java *******/

public class StackException

extends java.lang.RuntimeException {

public StackException(String s) {

super(s); // just let my parent handle it

} // end constructor

} // end StackException

H - 15

  • StackArrayBased class
    • Implements StackInterface
    • Instances
      • Stacks
    • Private data fields
      • An array of Objects called items
      • The index top

An Array Based Implementation

H - 16 public class StackArrayBased implements StackInterface { } private items[]; // Assumes top of stack is at items[0] public StackArrayBased() { public boolean isEmpty() { public void push(E newItem) { public E pop() throws StackException { } public E peek() throws StackException { }

H - 17

An Implementation that Uses

the ADT LinkedList

  • The ADT LinkedList can be used to

represent the items in a stack

  • How do we implement the stack ADT

(e.g., push, pop, peek, etc.) if the

elements of the stack are stored in a

LinkedList?

H - 18 public class StackLinkedListBased implements StackInterface { } private LinkedList items; // Assumes top of stack is at position 0 public StackLinkedListBased() { public boolean isEmpty() { public void push(E newItem) { public E pop() throws StackException { } public E peek() throws StackException { } private LinkedList items; // Assumes top of stack is at position 0 public StackLinkedListBased() { items = new LinkedList(); } public boolean isEmpty() { return items.isEmpty(); } public void push(E newItem) { items.add(0, newItem); } public E pop() throws StackException { if (!isEmpty()) return items.remove(0); else throw new StackException("Stack Exception on pop: stack empty"); } public E peek() throws StackException { if (!isEmpty()) return items.get(0); else throw new StackException("Stack Exception on peek: stack empty"); } H - 19

A Client Program

public class StackTest {

public static void main(String[] args) {

StackLinkedListBased stack =

new StackLinkedListBased();

for (int i=0; i<10; i++) {

stack.push(i);

} // end for

for (int j=0; j<15; j++) {

System.out.println(stack.pop());

} // end for

} // end main

What’s the problem? H - 20

Catching an Exception

public class StackTest {

public static void main(String[] args) {

StackLinkedListBased stack =

new StackLinkedListBased();

for (int i=0; i<10; i++) {

stack.push(i);

} // end for

for (int j=0; j<15; j++) {

try {

System.out.println(stack.pop());

} catch (StackException ex) {

System.out.println(“Empty stack!”);

break;

} // end for

} // end main

What changes are needed if we do not want to use a LinkedList implementation?