Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

Similar presentations


Presentation on theme: "1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,"— Presentation transcript:

1 1 Stacks

2 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out, or simply LIFO

3 3 ADT Stack Operations 1. Create an empty stack 2. Determine whether a stack is empty 3. Add a new item to the stack (push) 4. Remove from the stack the item that was added most recently (pop) 5. Remove all items from the stack 6. Retrieve from the stack the item that was added most recently

4 4 Pseudocode for the ADT Stack Operations createStack() //Creates an empty stack isEmpty() //Determines whether a stack is empty push(newItem) throws StackException /*Adds newItem to the top of the stack. Throws StackException if the insertion is not successful */ pop() throws StackException /*Retrieves and then removes the top of the stack (the item that was added most recently). Throws StackException if the deletion is not successful */

5 5 Pseudocode for the ADT Stack Operations popAll() //Removes all items from the stack peek() throws StackException /* Retrieves the top of the stack. That is, peek retrieves the item that was added most recently. Retrieval does not change the stack. Throws StackException if the retrieval is not successful */

6 6 Simple Applications of the ADT Stack - Checking for Balanced Braces Curly braces, “{“ and “}” delimits groups of statements To balance, keep track of each unmatched “{“ and discard one each time you encounter a “}” Push each “{“ encountered onto a stack and pop one off each time you encounter a “}”

7 7 Draft solution - Checking for Balanced Braces while (not at the end of the string) { if (the next character is a ‘{‘ ) { stack.push( ‘{‘ ) } else if (the character is a ‘}’ ) { openBrace = stack.pop() } // end if } //end while Requirements for balanced braces: 1.Each time you encounter a “}”, it matches an already encountered “{“ 2.When you reach the end of the string, you have matched each “{“

8 8 Detailed solution – Check a string for Balanced Braces stack.createStack() bancedSoFar = true i = 0 while (balancedSoFar and i < length of aString) { i++ //push an open brace if (ch is ‘{‘ ) { stack.push( ‘{‘ ) } //close brace else if ( ch is ‘}’ ) { if (! stack.isEmpty() ) { openBrace = stack.pop() //pop a matching open brace } else { //no matching open brace balancedSoFar = false } // end if // ignore all characters other than braces } // end while

9 9 Detailed solution – Check a string for Balanced Braces if ( balancedSoFar and stack.isEmpty() ) { aString has balanced braces } else { aString does not have balanced braces } // end if Input string {a{b}c} { {{{{{ Stack as algorithm executes 1234 1.push “{“ 2.push “{“ 3.pop 4.pop Stack empty  balanced

10 10 Implementation of the ADT Stack public interface StackInterface { public boolean isEmpty(); //Determines whether the stack is empty. //Precondition: None. //Postcondition: Returns true if the stack is empty; //otherwise returns false public void popAll(); //Removes all the items from the stack. //Precondition: None //Postcondition: Stack is empty. public void push(Object newItem) throws StackException; //Adds an item to the top of a stack //Precondition: newItem is the item to be added //Postcondition: If insertion is successful, newItem is on //the top of the stack. //Exception: Some implementation may throw a //StackException when newItem cannot be placed on the //stack.

11 11 Implementation of the ADT Stack public object pop() throws StackException; //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 f the stack is empty public Object peek() throws StackException; //Retrieves 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 }//end StackInterface

12 12 Class StackException public class StackException extends java.lang.RuntimeException { public StackException(String s) { super(s); }// end constructor }// end StackException

13 13 Implementations of the ADT stack that use (a) an array; (b) a linked list; (c) an ADT list 30 20 10 Array top 30 20 10 Linked list top 30 20 10 ADT list top (a) (b) (c)

14 14 An Array-Based Implementation of the ADT Stack 5 13 7 10 … items 012k k top MAX_STACK - 1 Array indexes public class StackArrayBased implements StackInterface { final int MAX_STACK = 50; //maximum size of stack private Object items[]; private int top; public StackArrayBased() { items = new Object[MAX_STACK]; top = -1; } // end default constructor

15 15 An Array-Based Implementation of the ADT Stack public boolean isEmpty() { return top < 0; }// end isEmpty public boolean isFull() { return top == MAX_STACK – 1; } // end isFull public void push(Object newItem) throws StackException { if ( ! isFull()) { items[++top] = newItem; } else { throw new StackException(“SatckException on push: stack full“); } // end if }// end push

16 16 public void popAll() { items = new Object[MAX_STACK]; top = -1; }// end popAll public Object pop() throws StackException { if (!isEmpty()) { return items[top--]; } else { throws new StackException(“StackException on pop: Stack empty”); } // end if } // end pop public Object peek() throws StackException { if (!isEmpty()) { return items[top]; } else { throws new StackException(“StackException on peek: Stack empty”); } // end if } // end peek }// end StackArrayBased

17 17 Using the ADT stack … public class StackTest { public static final int MAX_ITEMS = 15; public static void main(String[] args) { StackArrayBased stack = new StackArrayBased(); Integer items[] = new Integer[MAX_ITEMS]; for (int i = 0; i < MAX_ITEMS; i++){ items[i] = new Integer(i); if (!stack.isFull()){ stack.push(items[i]); }// end if }// end for while (!stack.isEmpty()){ //cast results of pop to Integer System.out.println((Integer)(stack.pop())); } // end while …

18 18 A Reference-Based Implementation of the ADT Stack public class StackReferenceBased implements StackInterface { private Node top; public StackReferenceBased() { top = null; }// end default constructor public boolean isEmpty() { return top == null; }// end isEmpty public void push(Object newItem){ top = new Node (newItem, top); }// end push public Object pop() throws StackException { if (!isEmpty()) { Node temp = top; top = top.getNext(); return temp.getItem(); }

19 19 A Reference-Based Implementation of the ADT Stack else { throw new StackException(“StackException on pop: Stack empty”); }// end if }// end pop public void popAll() { top = null; }// end popAll public Object peek() throws StackException { if (!isEmpty()) { return top.getItem(); } else { throw new StackException(“StackException on peek: Stack empty”); }// end if }// end peek } // end StackReferenceBased

20 20 Your Turn Provide implementation of the ADT stack using the ADT list.


Download ppt "1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,"

Similar presentations


Ads by Google