1 stacks. 2 a stack has the property that the last item placed on the stack will be the first item...
TRANSCRIPT
1
Stacks
2
Stacks
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
ADT Stack Operations
1. Create an empty stack2. Determine whether a stack is
empty3. 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 stack6. Retrieve from the stack the item
that was added most recently
4
Pseudocode for the ADT Stack Operations
createStack()//Creates an empty stackisEmpty()//Determines whether a stack is emptypush(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
Pseudocode for the ADT Stack Operations
popAll()//Removes all items from the stackpeek() 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
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
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
Detailed solution – Check a string for Balanced Braces
stack.createStack()bancedSoFar = truei = 0while (balancedSoFar and i < length of aString) { i++//push an open braceif (ch is ‘{‘ ) {
stack.push( ‘{‘ ) }
//close braceelse if ( ch is ‘}’ ) { if (! stack.isEmpty() ) {
openBrace = stack.pop() //pop a matching open brace
} else { //no matching open
bracebalancedSoFar = false
} // end if// ignore all characters other than braces} // end while
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 executes1 2 3 4
1. push “{“
2. push “{“
3. pop
4. pop
Stack empty balanced
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
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 emptypublic 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
Class StackException
public class StackException extends java.lang.RuntimeException {public StackException(String s) {
super(s);} // end constructor
} // end StackException
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
top30
20
10
ADT list
top
(a) (b) (c)
14
An Array-Based Implementation of the ADT Stack
5 13 7 10 …
items
0 1 2 k
k
top
MAX_STACK - 1Array indexes
public class StackArrayBased implements StackInterface {final int MAX_STACK = 50; //maximum size of stackprivate Object items[];private int top;
public StackArrayBased() {items = new Object[MAX_STACK];top = -1;
} // end default constructor
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
public void popAll() {items = new Object[MAX_STACK];top = -1;
} // end popAllpublic Object pop() throws StackException {
if (!isEmpty()) {return items[top--];
}else {throws new StackException(“StackException on pop: Stack empty”);} // end if
} // end poppublic 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
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 IntegerSystem.out.println((Integer)(stack.pop()));
} // end while…
18
A Reference-Based Implementation of the ADT
Stack
public class StackReferenceBased implements StackInterface {private Node top;public StackReferenceBased() {
top = null;} // end default constructorpublic boolean isEmpty() {
return top == null;} // end isEmptypublic void push(Object newItem) {
top = new Node (newItem, top);} // end pushpublic Object pop() throws StackException {
if (!isEmpty()) {Node temp = top;top = top.getNext();return temp.getItem();
}
19
A Reference-Based Implementation of the ADT
Stackelse {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
Your Turn
Provide implementation of the ADT stack using the ADT list.