You are on page 1of 25

CSE/IT 213 - Stacks and Graphs

New Mexico Tech


October 3, 2011

Generics
A generic class is a class that allows you to specify the
data type of one or more fields as a parameter.
General form of a generic class
ClassName<E1,E2,...,En>, where Ei are placeholders for
some reference type.
Use inheritance to limit the types of classes generic
classes could use
public ClassName <T extends P> restricts T to be of class
P and its subclasses
1

and for polymorphism we used wildcards


public ClassName <?

extends P>

Stack
What is a stack? Basic data structure.
Lets define an interface that defines stack-ness.
What constitutes stack-ness?

public interface StackInterface<T> {


/** True if stack is empty. */
boolean isEmpty ();
/** how many items in the stack. */
int size ();
/** get the top item in the stack but do not remove it */
T getTop ();
/** Remove and return the top item of the stack */
T pop ();
/** Add an item to the top of the stack */
3

void push (T x);


/** Get the index of the most-recently inserted item */
int lastIndexOf (T x);
}

How to implement Stack?


Use an ArrayList to provide the storage for a Stack.
This allows us to use ArrayLists methods.

import java.util.*;
class Stack<T> implements StackInterface<T> {
private ArrayList<T> stack;
//constructors
/** default of ArrayList is 10 items */
public Stack() {
4

stack = new ArrayList<T>();


}
public Stack(int initSizeOfStack) {
stack = new ArrayList<T>(initSizeOfStack);
}
//methods
public boolean isEmpty () {
return stack.isEmpty(); //true if no elements
}
public int size () {
return stack.size();
}

public T getTop () {
if (!stack.isEmpty())
return stack.get(stack.size() - 1);
else
return null;
}
public T pop () {
if (stack.isEmpty()) //stack contains no elements
return null;
return stack.remove(stack.size() - 1);
}

public void push(T x) {


stack.add(x); //using ArrayList methods
}
public int lastIndexOf (T x) {
return stack.lastIndexOf(x);
}
}

Testing the Stack


public class StackTest {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(17);
stack.push(23);
stack.push(29);
stack.push(31);
stack.push(37);
while(!stack.isEmpty()) {
System.out.println(stack.getTop());
5

stack.pop();
}
}
}
37
31
29
23
17

Uses of Stacks
Balanced parenthesis
postfix evaluation
Graphs

Balanced parenthesis
Mathematics, source code, markup languages depend
on balanced parenthesis (or braces, brackets, etc) to
operate correctly.
For example this expression evaluates correctly
[(a + b)2 + ecos(x+y)] sin(e(xy)) + (a b3)
[ () () ] ( () ) ()
while this one doesnt as it has doesnt have a matching
parenthesis
[(a + b)2 + ecos(x+y)] sin(e(xy) + (a b3)
[ () () ] ( () ()
7

Using a stack to check for balanced parenthesis


Start with an empty stack
Scan the expression from left right
If you read a left parentheses (or brace, etc.) push it
onto the stack
When you encounter a right parentheses check that the
top of the stack contains a matching left parenthesis.
If so, pop the top item off the stack
An error occurs if right parenthesis occurs and there is
not a matching left parenthesis.
When finished reading expression and stack is empty,
expression contains balanced parenthesis.
8

For example, to evaluate {[x+b]+(9[x])}


stack
empty
{
{[
{[
{[
{[
{
{
{(
{(
{([
{([
{(
{
empty

input string
{[x+b]+(9[x])}
[x+b]+(9[x])}
x+b]+(9[x])}
+b]+(9[x])}
b]+(9[x])}
]+(9[x])}
+(9[x])}
(9[x])}
9[x])}
[x])}
x])}
])}
)}
}
end of string

action
push {
push [
read x
read t
read b
read ] pop matching left [
read +
push (
read 9
push [
read x
read ] pop matching left [
read ) pop matching left )
read } pop matching left }
empty stack balanced
9

Evaluating postfix
n1 op n2 expressions are called infix, where op represents
an operator and n1, n2 are operands.
n1 n2 op are called postfix or RPN. An advantage RPN
has over infix is there is no need for parenthesis.
infix
(3 + 5) 4
(x y z)/(u + v)

RPN
35 + 4
xy z uv + /

10

Algorithm for solving RPN


Scan RPN expression from left right
When you encounter an operand push it onto the stack
(stack nn)
When you encounter an operator pop off two numbers
from stack
right pop stack
lef t pop stack
Evaluate lef t op right and push onto stack
stack (lef t op right)
When done with scanning expression, the answer should
remain as the only element in the stack
11

Evaluate 3 5 + 4
stack
empty
3
3 5
3
empty
8
8 4
8
empty
32

input string
35 + 4
5 + 4
+4
4
4
4

empty
empty
empty

action
read 3, push 3 onto stack
read 5, push 5 onto stack
read +, pop 5 from stack
pop 3 from stack
push 5 + 3 = 8 onto stack
read 4, push 4 onto stack
read *, pop 4 from stack
pop 8 from stack
push 8 4 = 32 onto stack
done, string is empty

12

Graphs
A graph is a collection of vertices and edges.
Vertices, also called nodes, can have names and other
properties,
Edges are connections between two vertices.

13

A path from vertex x to y is a list of vertices in which


successive vertices are connected by edges in the graph.
A graph is connected if there is a path from every node
to every other node.
Think of edges as rods, connected means if you pick
up the graph every vertex stays in place.
A simple path is a path in which no vertex is repeated.
A cycle is a path that is simple but the first and last
vertex are the same.
Graphs with no cycles are called trees
14

A group of disconnected tress is called a forest


A spanning tree of a graph is subgraph that contains
all the vertices of the graph, but only enough edges to
form a tree.
Adding an edge to a tree between any unconnected
vertices will form a cycle.
A tree with n vertices has n 1 edges.
Graphs with n vertices and less than n 1 edges cannot
be connected.
Graphs with n vertices and more than n 1 edges must
have a cycle

Graphs with n vertices and n1 edges is not necessarily


a tree.
The number of edges En in a graph with n vertices will
range from 0 En n(n1)
2
Graphs are called undirected when there is no direction to the edge joining vertices. For example, a twoway road (edge) conecting cities (vertices) is an undirected graph.
Graphs are called directed if going from vertices u and v
is different than going from v to u. Think of a one-way
road.

Graphs are called weighted if the edges store some information that model some relationship between vertices. For instance edges as roads, one could assign
the miles between vertices (cities).

Representing Graphs
First step is convert vertex names to an integer between
1 and n, where n is the number of vertices. Allows you
to use an array indexing to access vertices.
Then can use an adjacency matrix to represent a graph.
An adjacency matrix is a n n boolean valued matrix.
Where a[i][j] = 1 represents that there is an edge between vertex i and vertex j. a[j][i] is also assigned a 1.
While this adds to storage, makes algorithms easier.
Often assume that there is an edge from each vertex
to itself. So a[i][i] = 1. That is the diagonal of the
matrix is set to 1. In other cases, it may be easier to
assign 0 to the diagonal.
15

You might also like