06 - Stacks
06 - Stacks
Stacks khaled.nagi@alexu.edu.eg 1
Stacks
Stacks
Array-based implementations
Linked list implementations
Stacks khaled.nagi@alexu.edu.eg 2
Stacks
Stacks khaled.nagi@alexu.edu.eg 3
Stacks (ǁ)
Stacks khaled.nagi@alexu.edu.eg 4
Stacks
Stacks khaled.nagi@alexu.edu.eg 5
The Stack Abstract Data Type
A stack is an abstract data type (ADT) that supports two main methods:
Push(o): Inserts object o onto top of stack.
Input: Object; Output: none
Pop(): Removes the top object from the stack and returns it; if stack is empty
an error occurs.
Input: none; Output: Object
Stacks khaled.nagi@alexu.edu.eg 6
The Stack Abstract Data Type
Stacks khaled.nagi@alexu.edu.eg 7
Example Stack Operations
Stacks khaled.nagi@alexu.edu.eg 8
Abstract Classes
Stacks khaled.nagi@alexu.edu.eg 9
Code
Stacks khaled.nagi@alexu.edu.eg 10
Interfaces
Stacks khaled.nagi@alexu.edu.eg 11
Code
Stacks khaled.nagi@alexu.edu.eg 12
A formal parameter type that is an interface can accept as an actual
parameter any class or subclass that implements the interface.
/** Some operations on Measurable's. */
public class MeasureUtil {
public static double maxArea(Measurable m1, Measurable m2) {
return(Math.max(m1.getArea(), m2.getArea()));
}
public static double totalArea(Measurable[] mArray) {
double total = 0;
for(int i=0; i<mArray.length; i++)
total = total + mArray[i].getArea();
return total;
}
}
Stacks khaled.nagi@alexu.edu.eg 13
(ǀ)
/** Test of MeasureUtil. Note that we could change the actual classes of
elements in the measurable array (as long as they implemented
Measurable) without changing
The rest of the code.
*/
public class MeasureTest {
public static void main(String[] args) {
Measurable[] measurables = {
new Rectangle(0, 0, 5.0, 10.0), //also implements measurable
new Rectangle(0, 0, 4.0, 9.0),
new Circle(0, 0, 4.0),
new Circle(0, 0, 5.0)
};
Stacks khaled.nagi@alexu.edu.eg 14
(ǁ)
System.out.print("Areas:");
for(int i=0; i<measurable.length; i++)
System.out.print(" " + measurable[i].getArea());
System.out.println();
System.out.println
("Larger of 1st, 3rd: " +
MeasureUtil.maxArea(measurables[0], measurable[2]) + "\nTotal area: " +
MeasureUtil.totalArea(measurables));
}
}
Stacks khaled.nagi@alexu.edu.eg 15
A Stack Interface in Java
Stacks khaled.nagi@alexu.edu.eg 16
A Stack Interface in Java
While the stack data structure is a “built-in” class of the JDK java.util
package,
It is possible and sometimes preferable to define your own interface
It is instructive to learn how to design and implement a stack "from scratch."
Stacks khaled.nagi@alexu.edu.eg 17
An Array-Based Stack
Stacks khaled.nagi@alexu.edu.eg 18
Pseudo Code
Stacks khaled.nagi@alexu.edu.eg 19
An Array-Based Stack
Stacks khaled.nagi@alexu.edu.eg 20
Array-Based Stack: a Java Implementation
Stacks khaled.nagi@alexu.edu.eg 21
Array-Based Stack: a Java Implementation
Stacks khaled.nagi@alexu.edu.eg 22
Array-Based Stack: a Java Implementation
Stacks khaled.nagi@alexu.edu.eg 23
Casting with a Generic Stack
Stacks khaled.nagi@alexu.edu.eg 24
Stacks in the Java Virtual Machine
Each process running in a Java program has its own Java method stack.
Each time a method is called, it is pushed onto the stack.
A frame in the stack stores information relevant to running and
suspended methods (i.e., local variables, actual parameters, return
values, etc.)
The choice of a stack for this operation allows Java to do several useful
things:
Perform recursive method calls. Conceptually, as regards the Java method
stack, there is no difference between a recursive call and a “regular” call.
Print stack traces so that users can locate an error.
Stacks khaled.nagi@alexu.edu.eg 25
Java Method Stack
Stacks khaled.nagi@alexu.edu.eg 26
A Linked List-based Stack
Stacks khaled.nagi@alexu.edu.eg 27
Should the top of the stack be at the head or at
the tail of the list?
Insert and delete elements at the head O(1)
Thus, it is more efficient to have the top of the stack at the head of the
list.
In order to perform operation size in constant time, we keep track of the
current number of elements in an instance variable.
Stacks khaled.nagi@alexu.edu.eg 28
…
Stacks khaled.nagi@alexu.edu.eg 29
A Stack Interface in Java
// update methods
public void push (Object element); // insert an element onto the stack
throws StackFullException; // thrown if overflow
public Object pop() // return and remove the top element of the stack
throws StackEmptyException; // thrown if called on an empty stack
}
Stacks khaled.nagi@alexu.edu.eg 30
Java Implementation of a Stack NodeStack Class
Stacks khaled.nagi@alexu.edu.eg 31
Java Implementation of a Stack NodeStack Class
Stacks khaled.nagi@alexu.edu.eg 32
Java Implementation of a Stack NodeStack Class
Stacks khaled.nagi@alexu.edu.eg 33
Reversing an Array Using a Stack – Non
Recursive Algorithm
The basic idea: push all the elements of the array in order into a stack
and then fill the array back up again by popping the elements off of the
stack.
Public static Integer[] reverse(Integer[] a)
{
ArrayStack s = new ArrayStack(a.length);
Integer[] b = new Integer[a.length];
for(int i = 0; i < a.length; i++)
s.push(a[i]);
for(int i = 0; i < a.length; i++)
b[i] = (Integer)(s.pop());
return b;
}
Stacks khaled.nagi@alexu.edu.eg 34
Reversing an Array Using a Stack – Recursive
Algorithm (ǀ)
The reversal of an array can be achieved by swapping the first and last
elements
Then recursively reversing the remaining elements in the array.
Algorithm ReverseArray(A,i,j):
Input: An array A and nonnegative integer indices i and j
Output: The reversal of the elements in A starting at index i and ending at j
if i < j then
Swap A[i] and A[j]
ReverseArray(A, i+1,j-1)
return
Stacks khaled.nagi@alexu.edu.eg 35
Reversing an Array Using a Stack – Recursive
Algorithm (ǁ)
Two base cases, namely, when i = j and when i > j:
if n is odd, we will reach the i = j case,
if n is even, we will reach the i > j case.
In either case, we terminate the algorithm, since a sequence with zero
elements or one element is trivially equal to its reversal
Stacks khaled.nagi@alexu.edu.eg 36
Java Method Stack
Stacks khaled.nagi@alexu.edu.eg 37
Applications Using Stacks
Stacks khaled.nagi@alexu.edu.eg 38
Matching Parentheses
Stacks khaled.nagi@alexu.edu.eg 39
An Algorithm for Parentheses Matching
Stacks khaled.nagi@alexu.edu.eg 40
(ǀ)
Algorithm ParenMatch(X,n):
Input: An array X of n tokens, each of which is either a grouping symbol,
a variable, an arithmetic operator, or a number
Output: true if and only if all the grouping symbols in X match
Let S be an empty stack
for i ← 0 to n – 1 {
if X[i] is an opening grouping symbol then
s.push(X[i])
else if X[i] is a closing grouping symbol then
if s.isEmpty() then
return false {nothing to match with}
if s.pop() does not match the type of X[i] then
return false {wrong type}
}
Stacks khaled.nagi@alexu.edu.eg 41
(ǁ)
if s.isEmpty() then
return true {every symbol matched}
else
return false {some symbols were never matched}
Assuming that the push and pop operations are implemented to run in
constant time, this algorithm runs in O(n), that is linear time
Stacks khaled.nagi@alexu.edu.eg 42
Matching Tags in an HTML Document
Stacks khaled.nagi@alexu.edu.eg 43
Stacks khaled.nagi@alexu.edu.eg 44
The same algorithm as for matching parentheses can be used to match
the tags in an HTML document.
Stacks khaled.nagi@alexu.edu.eg 45