0% found this document useful (0 votes)
2 views

8_ADTStack

Uploaded by

aaldayel2015
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

8_ADTStack

Uploaded by

aaldayel2015
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 103

1

STACKS
CS212: Data Structure
2

Stacks
• A stack is a container of objects that are inserted and
removed according to the last-in-first-out (LIFO)
principle.

• Objects can be inserted at any time, but only the last (the
most-recently inserted) object can be removed.
• Inserting an item is known as “Pushing” onto the stack.
“Popping” off the stack is synonymous with removing an
item
• Used in Operating system to implement method calls, and
in evaluating Expressions.
3

ADT Stack: Specification


Elements: The elements are of a generic type
<Type>. (In a linked implementation an element is
placed in a node)
Structure: the elements are linearly arranged, and
ordered according to the order of arrival, most
recently arrived element is called top.
Domain: the number of elements in the stack is
bounded therefore the domain is finite. Type of
elements: Stack
4

ADT Stack: Specification


Operations:
All operations operate on a stack S.
1. Method push (Type e)
requires: Stack S is not full.
input: Type e.
results: Element e is added to the stack as its most recently added
elements.
output: none.
2. Method pop (Type e)
requires: Stack S is not empty.
input: none
results: the most recently arrived element in S is removed and its
value assigned to e.
output: Type e.
3. Method empty (boolean flag)
input: none
results: If Stack S is empty then flag is true, otherwise false.
output: flag.
5

ADT Stack: Specification


Operations:
4. Method Full (boolean flag).
requires:
input: none
results: If S is full then Full is true, otherwise Full is
false.
output: flag.
6

Stack Interface
public interface Stack<T>{
public T pop( );
public void push(T e);
public boolean empty( );
public boolean full( );
}
7

ADT Stack (Linked-List)


T

null
8

ADT Stack (Linked-List): Element


public class Node<T> {
public T data;
public Node<T> next;

public Node () {
data = null;
next = null;
}

public Node (T val) {


data = val;
next = null;
}

// Setters/Getters?
}
9

ADT Stack (Linked-List): Implementation

public class LinkedStack<T> implements


Stack<T> {
private Node<T> top;

/* Creates a new instance of LinkStack */


public LinkedStack() {
top = null;
}
10

ADT Stack (Linked-List): Implementation

public class LinkedStack<T> implements


Stack<L> {
private Node<T> top;

/* Creates a new instance of LinkStack */


public LinkedStack() {
top = null; null T
}
11

ADT Stack (Linked-List): Implementation

public boolean empty(){


return top == null;
}

public boolean full(){


return false;
}
12

ADT Stack (Linked-List): Implementation


T

public boolean empty(){ false


return top == null;
}
null

public boolean full(){


return false;
true null T
}
13

ADT Stack (Linked-List): Implementation

public void push(T e){


Node<T> tmp = new Node<T>(e);
tmp.next = top;
top = tmp;
}
14

ADT Stack (Linked-List): Implementation

public void push(T e){


Node<T> tmp = new Node<T>(e);
tmp.next = top;
top = tmp;
}
null T

Example #1
15

ADT Stack (Linked-List): Implementation

public void push(T e){


Node<T> tmp = new Node<T>(e);
tmp.next = top;
tmp
top = tmp;
}
null T

Example #1
16

ADT Stack (Linked-List): Implementation

public void push(T e){


Node<T> tmp = new Node<T>(e);
tmp.next = top;
tmp
top = tmp;
}
null T

Example #1
17

ADT Stack (Linked-List): Implementation

public void push(T e){


Node<T> tmp = new Node<T>(e);
tmp.next = top;
tmp
top = tmp; T
}
null

Example #1
18

ADT Stack (Linked-List): Implementation

public void push(T e){


Node<T> tmp = new Node<T>(e);
tmp.next = top;
top = tmp; T
}
null

Example #2
19

ADT Stack (Linked-List): Implementation

public void push(T e){


tmp
Node<T> tmp = new Node<T>(e);
tmp.next = top;
top = tmp; T
}
null

Example #2
20

ADT Stack (Linked-List): Implementation

public void push(T e){


tmp
Node<T> tmp = new Node<T>(e);
tmp.next = top;
top = tmp; T
}
null

Example #2
21

ADT Stack (Linked-List): Implementation

public void push(T e){


tmp
Node<T> tmp = new Node<T>(e); T
tmp.next = top;
top = tmp;
}
null

Example #2
22

ADT Stack (Linked-List): Implementation

public void push(T e){


Node<T> tmp = new Node<T>(e); T
tmp.next = top;
top = tmp;
}
null

Example #3
23

ADT Stack (Linked-List): Implementation

tmp

public void push(T e){


Node<T> tmp = new Node<T>(e); T
tmp.next = top;
top = tmp;
}
null

Example #3
24

ADT Stack (Linked-List): Implementation

tmp

public void push(T e){


Node<T> tmp = new Node<T>(e); T
tmp.next = top;
top = tmp;
}
null

Example #3
25

ADT Stack (Linked-List): Implementation

tmp
T
public void push(T e){
Node<T> tmp = new Node<T>(e);
tmp.next = top;
top = tmp;
}
null

Example #3
26

ADT Stack (Linked-List): Implementation

T
public void push(T e){
Node<T> tmp = new Node<T>(e);
tmp.next = top;
top = tmp;
}
null

Example #3
27

ADT Stack (Linked-List): Implementation

public T pop(){
T e = top.data;
top = top.next;
return e;
}
}
28

ADT Stack (Linked-List): Implementation

T
public T pop(){
T e = top.data;
top = top.next;
return e;
}
null
}
Example #1
29

ADT Stack (Linked-List): Implementation

T
public T pop(){
T e = top.data;
top = top.next;
return e;
}
null
}
Example #1
30

ADT Stack (Linked-List): Implementation

public T pop(){
T e = top.data; T
top = top.next;
return e;
}
null
}
Example #1
31

ADT Stack (Linked-List): Implementation

public T pop(){
T e = top.data; T
top = top.next;
return e;
}
null
}
Example #1
32

ADT Stack (Linked-List): Implementation

public T pop(){
T e = top.data; T
top = top.next;
return e;
}
null
}
Example #1
33

ADT Stack (Linked-List): Implementation

public T pop(){
T e = top.data; T
top = top.next;
return e;
}
null
}
Example #2
34

ADT Stack (Linked-List): Implementation

public T pop(){ e

T e = top.data; T
top = top.next;
return e;
}
null
}
Example #2
35

ADT Stack (Linked-List): Implementation

public T pop(){ e

T e = top.data;
top = top.next;
return e; T
}
null
}
Example #2
36

ADT Stack (Linked-List): Implementation

public T pop(){ e

T e = top.data;
top = top.next;
return e; T
}
null
}
Example #2
37

ADT Stack (Linked-List): Implementation

public T pop(){
T e = top.data;
top = top.next;
return e; T
}
null
}
Example #2
38

ADT Stack (Linked-List): Implementation

public T pop(){
T e = top.data;
top = top.next;
return e; T
}
null
}
Example #3
39

ADT Stack (Linked-List): Implementation

public T pop(){
T e = top.data;
top = top.next; e

return e; T
}
null
}
Example #3
40

ADT Stack (Linked-List): Implementation

public T pop(){
T e = top.data;
top = top.next; e

return e;
}
null T
}
Example #3
41

ADT Stack (Linked-List): Implementation

public T pop(){
T e = top.data;
top = top.next; e

return e;
}
null T
}
Example #3
42

ADT Stack (Linked-List): Implementation

public T pop(){
T e = top.data;
top = top.next;
return e;
}
null T
}
Example #3
43

ADT Stack (Linked-List): Implementation

public T pop(){
T e = top.data;
top = top.next;
return e;
}
null T
}
Example #3
44

ADT Stack (Array)


maxsize
n

n-1

.
.
.
.

2 T

0
45

ADT Stack (Array): Representation


public class ArrayStack<T> implements Stack<L> {
private int maxsize;
private int top;
private T[] nodes;

/** Creates a new instance of ArrayStack */


public ArrayStack(int n) {
maxsize = n;
top = -1;
nodes = (T[]) new Object[n];
}
46

ADT Stack (Array): Representation


max
public class ArrayStack<T> implements Stack<L>
4 {
private int maxsize;
private int top; 3
private T[] nodes;
2

/** Creates a new instance of ArrayStack */ 1


public ArrayStack(int n) {
0
maxsize = n;
top = -1; T
nodes = (T[]) new Object[n];
}
47

ADT Stack (Array): Implementation

public boolean empty(){


return top == -1;
}

public boolean full(){


return top == maxsize - 1;
}
48

ADT Stack (Array): Implementation


max max
4 4

public boolean empty(){


3 3
return top == -1;
} 2 2

1 T 1

public boolean full(){ 0 0


return top == maxsize - 1;
T
}
false true
49

ADT Stack (Array): Implementation


max max
4 4

public boolean empty(){


3 3 T
return top == -1;
T
} 2 2

1 1

public boolean full(){ 0 0


return top == maxsize - 1;
}
false true
50

ADT Stack (Array): Implementation

public void push(T e){


nodes[++top] = e;
}

public T pop(){
return nodes[top--];
}
}
51

ADT Stack (Array): Implementation


max
4

public void push(T e){


3
nodes[++top] = e;
} 2

1
public T pop(){
0
return nodes[top--];
} T

} Example #1
52

ADT Stack (Array): Implementation


max
4

public void push(T e){


S1 ← ++top 3
nodes[++top] = e; nodes[S1] = e
} 2

1
public T pop(){ T
0
return nodes[top--];
}
} Example #1
53

ADT Stack (Array): Implementation


max
4

public void push(T e){


← ++top 3
nodes[++top] = e; S1
nodes[S1] = e
} 2

1
public T pop(){ T
0
return nodes[top--];
e
}
} Example #1
54

ADT Stack (Array): Implementation


max
4

public void push(T e){


3
nodes[++top] = e;
} 2

1
public T pop(){ T
0
return nodes[top--];
}
} Example #2
55

ADT Stack (Array): Implementation


max
4

public void push(T e){


S1 ← ++top 3
nodes[++top] = e; nodes[S1] = e
} 2

1 T
public T pop(){
0
return nodes[top--];
}
} Example #2
56

ADT Stack (Array): Implementation


max
4

public void push(T e){


← ++top 3
nodes[++top] = e; S1
nodes[S1] = e
} 2

1 T
public T pop(){ e
0
return nodes[top--];
}
} Example #2
57

ADT Stack (Array): Implementation


max
4

public void push(T e){


3
nodes[++top] = e;
} 2

1 T
public T pop(){
0
return nodes[top--];
}
} Example #3
58

ADT Stack (Array): Implementation


max
4

public void push(T e){


3
nodes[++top] = e;
} 2

1 T
S1 ← nodes[top]
public T pop(){ top--
return S1 0
return nodes[top--];
}
} Example #3
59

ADT Stack (Array): Implementation


max
4

public void push(T e){


3
nodes[++top] = e;
} 2

S1 ← nodes[top] 1
public T pop(){ top--
T
return S1 0
return nodes[top--];
}
} Example #3
60

ADT Stack (Array): Implementation


max
4

public void push(T e){


3
nodes[++top] = e;
} 2

1
public T pop(){ T
0
return nodes[top--];
}
} Example #4
61

ADT Stack (Array): Implementation


max
4

public void push(T e){


3
nodes[++top] = e;
} 2

S1 ← nodes[top] 1
public T pop(){ top--
T
return S1 0
return nodes[top--];
}
} Example #4
62

ADT Stack (Array): Implementation


max
4

public void push(T e){


3
nodes[++top] = e;
} 2

S1 ← nodes[top] 1
public T pop(){ top--
return S1 0
return nodes[top--];
} T

} Example #4
63

ADT Stack (Array): Implementation


max
4

public void push(T e){


3
nodes[++top] = e;
} 2

1
public T pop(){
0
return nodes[top--];
} T

} Example #4
Applications of Stacks
 Some applications of stacks are:
◦ Balancing symbols.
◦ Computing or evaluating postfix expressions.
◦ Converting expressions from infix to postfix.

64
65

1. Balancing Symbols
• Expressions: mathematical (a + ((b-c)*d)) or
programs have delimiters.
begin {
S1 S1
S2 {
begin S2
S3 S3
begin }
…. S4
end }
end
end
66

1. Balancing Symbols
• Delimiters must be balanced.
• One of the common use of the stacks is to parse certain
kinds of expressions or string text.
• Write a program that verifies the delimiters in a line of text
or expression typed by the user.
• a*(b+c) //This expression is right
• b/[a*(b+c)] //This expression is right
• {a*(b+c]} //This expression is wrong
67

1. Balancing Symbols

• Read characters from the start of the expression to


the end.
• If the token is a starting delimiter, then push on to the
stack.
• If the token is a closing delimiter, then pop from the stack.
• If symbol from this pop operation matches the closing delimiter, then we carry
on.
• If not, or the stack was empty, then we have unbalanced symbols (report an
error).

• If stack is empty at the end of expression, we have


balanced symbols.
• If not (stack is not empty), then we have
unbalanced symbols (report an error).
68

1. Balancing Symbols
• Input : expression
• Output: True if and only if delimiters are balanced
• Let S be empty Stack
• Let n be number of characters
• for i=0 n-1
• If expression[i] is a Opening delimiter, then
• S.push(expression[i]).
• else If expression[i] is a closing delimiter, then
• If the S is empty
• return false unbalanced symbols
• symbol=S.pop().
• If symbol does not matches the closing delimiter
• return false unbalanced symbols.
• If S is empty
• return true balanced symbols.
• else
• return false unbalanced symbols
69

2. Postfix Expressions
• Evaluating Postfix Expressions:
• Infix expression: 4.99*1.06+5.99+6.99*1.06
• Value 18.69 correct parenthesis used.
• Value 19.37 incorrect  no parenthesis used.
• In postfix form, above expression becomes:
4.99 1.06 * 5.99 + 6.99 1.06*+
Advantage: no brackets are needed and a stack can be used to
compute the expression.
70

2. Postfix Expressions
• Example:
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read:
• pop two numbers from the stack
• carry out the operation on them
• push the result back on the stack.
71

2. Postfix Expressions
• Example:
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read:
• pop two numbers from the stack
• carry out the operation on them
• push the result back on the stack.
72

2. Postfix Expressions
• Example:
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read:
• pop two numbers from the stack
• carry out the operation on them
6
• push the result back on the stack.
73

2. Postfix Expressions
• Example:
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read:
• pop two numbers from the stack 5
• carry out the operation on them
6
• push the result back on the stack.
74

2. Postfix Expressions
• Example:
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read: 2
• pop two numbers from the stack 5
• carry out the operation on them
6
• push the result back on the stack.
75

2. Postfix Expressions
• Example:
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
3
• When a number is read push it on the stack.
• When an operator is read: 2
• pop two numbers from the stack 5
• carry out the operation on them
6
• push the result back on the stack.
76

2. Postfix Expressions
• Example:
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
3
• When a number is read push it on the stack.
• When an operator is read: 2
• pop two numbers from the stack 5
• carry out the operation on them
6
• push the result back on the stack.
77

2. Postfix Expressions
• Example:
2+3=5
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read:
• pop two numbers from the stack 5
• carry out the operation on them
6
• push the result back on the stack.
78

2. Postfix Expressions
• Example:
2+3=5
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read: 5
• pop two numbers from the stack 5
• carry out the operation on them
6
• push the result back on the stack.
79

2. Postfix Expressions
• Example:
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
8
• When a number is read push it on the stack.
• When an operator is read: 5
• pop two numbers from the stack 5
• carry out the operation on them
6
• push the result back on the stack.
80

2. Postfix Expressions
• Example:
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
8
• When a number is read push it on the stack.
• When an operator is read: 5
• pop two numbers from the stack 5
• carry out the operation on them
6
• push the result back on the stack.
81

2. Postfix Expressions
• Example:
5 * 8 = 40
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read:
• pop two numbers from the stack 5
• carry out the operation on them
6
• push the result back on the stack.
82

2. Postfix Expressions
• Example:
5 * 8 = 40
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
4
• When an operator is read: 0
• pop two numbers from the stack 5
• carry out the operation on them
• push the result back on the stack. 6
83

2. Postfix Expressions
• Example:
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
4
• When an operator is read: 0
• pop two numbers from the stack 5
• carry out the operation on them
• push the result back on the stack. 6
84

2. Postfix Expressions
• Example:
5 + 40 = 45
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read:
• pop two numbers from the stack
• carry out the operation on them
6
• push the result back on the stack.
85

2. Postfix Expressions
• Example:
5 + 40 = 45
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read:
• pop two numbers from the stack 4
5
• carry out the operation on them
• push the result back on the stack. 6
86

2. Postfix Expressions
• Example:
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read: 3
• pop two numbers from the stack 4
5
• carry out the operation on them
• push the result back on the stack. 6
87

2. Postfix Expressions
• Example:
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read: 3
• pop two numbers from the stack 4
5
• carry out the operation on them
• push the result back on the stack. 6
88

2. Postfix Expressions
• Example:
45 + 3 = 48
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read:
• pop two numbers from the stack
• carry out the operation on them
6
• push the result back on the stack.
89

2. Postfix Expressions
• Example:
45 + 3 = 48
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read:
• pop two numbers from the stack 4
8
• carry out the operation on them
• push the result back on the stack. 6
90

2. Postfix Expressions
• Example:
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read:
• pop two numbers from the stack 4
8
• carry out the operation on them
• push the result back on the stack. 6
91

2. Postfix Expressions
• Example:
6 * 48 = 288
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read:
• pop two numbers from the stack
• carry out the operation on them
• push the result back on the stack.
92

2. Postfix Expressions
• Example:
6 * 48 = 288
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read:
• pop two numbers from the stack
• carry out the operation on them 28
8
• push the result back on the stack.
93

2. Postfix Expressions
• Example:
End!
• infix: 6*(5+((2+3)*8)+3)
• postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression:
• Read the postfix expression left to right.
• When a number is read push it on the stack.
• When an operator is read:
• pop two numbers from the stack
• carry out the operation on them 28
result 8
• push the result back on the stack.
94

3. Converting from infix to postfix


Assume the infix expression is a string of tokens delimited by spaces.
The operator tokens are *, /, +, and -, along with the left and right
parentheses, ( with ). The operand tokens are the single-character
identifiers A, B, C, and so on.
The following steps will produce a string of tokens in postfix order.
1. Create an empty stack called opstack for keeping operators. Create an
empty list for output.
2. Scan the token list from left to right.
• If the token is an operand, append it to the end of the output list.
• If the token is a left parenthesis, push it on the opstack .

• If the token is a right parenthesis, pop the opstack until the


corresponding left parenthesis is removed. Append each operator to
the end of the output list.
• If the token is an operator, *, /, +, or -, push it on the opstack. However,
first remove any operators already on the opstack that have higher or
equal precedence and append them to the output list.
3. When the input expression has been completely processed, check the
opstack. Any operators still on the stack can be removed and appended
to the end of the output list.
Goodrich, Tamassia 2010 © 95

Applications of Stacks
• Direct applications
• Page-visited history in a Web browser
• Undo sequence in a text editor
• Chain of method calls in the Java Virtual Machine
• Indirect applications
• Auxiliary data structure for algorithms
• Component of other data structures
Goodrich, Tamassia 2010 © 96

Method Stack in the JVM


• The Java Virtual Machine (JVM) main() {
keeps track of the chain of int i = 5;
foo(i); bar
active methods with a stack } PC = 1
• When a method is called, the foo(int j) { m=6
JVM pushes on the stack a int k;
frame containing k = j+1;
foo
• Local variables and return value bar(k);
} PC = 3
• Program counter, keeping track of
bar(int m) {
j=5
the statement being executed k=6

• When a method ends, its frame
}
is popped from the stack and main
control is passed to the method PC = 2
on top of the stack i=5
• Allows for recursion
97

Reverse a List using Stack


public class Tester {

// … other methods here

public void intReverse(List<Integer> l) {


Stack<Integer> s = new Stack<Integer>();

l.findFirst();
while(!l.empty()) {
s.push(l.retrieve());
l.remove();
}

while(!s.empty())
l.insert(s.pop());
}
}
Goodrich, Tamassia 2010 © 98

Parentheses Matching
• Each “(”, “{”, or “[” must be paired with a matching “)”, “}”,
or “]”
• correct: ( )(( )){([( )])}
• correct: ((( )(( )))){([( )])}
• incorrect: )(( )){([( )])}
• incorrect: ({[ ])}
• incorrect: (
Goodrich, Tamassia 2010 © 99

Parentheses Matching Algorithm


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 do
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}
if S.isEmpty() then
return true {every symbol matched}
else
return false {some symbols were never matched}
Goodrich, Tamassia 2010 © 100

HTML Tag Matching


>For fully-correct HTML, each <name> should pair with a matching </name

<body> The Little Boat


<center>
<h1> The Little Boat </h1>
</center> The storm tossed the little boat
<p> The storm tossed the little like a cheap sneaker in an old
boat like a cheap sneaker in an washing machine. The three
old washing machine. The three drunken fishermen were used to
drunken fishermen were used to such treatment, of course, but not
such treatment, of course, but
not the tree salesman, who even as
the tree salesman, who even as
a stowaway now felt that he a stowaway now felt that he had
had overpaid for the voyage.</p> overpaid for the voyage.
<ol>
<li> Will the salesman die? </li> 1. Will the salesman die?
<li> What color is the boat? </li> 2. What color is the boat?
<li> And what about Naomi? </li> 3. And what about Naomi?
</ol>
</body>
Stallmann 2010 © 101

Evaluating Arithmetic Expressions

7 + ) )2 * 3( – 14( = 7 + 2 * 3 – 14
Operator precedence
* has precedence over +/–

Associativity
operators of the same precedence group
evaluated from left to right
Example: (x – y) + z rather than x – (y + z)

Idea: push each operator on the stack, but first pop and perform higher and
.equal precedence operations
102

Algorithm for Evaluating Expressions


Two stacks: Algorithm EvalExp()
• opStk holds operators Input: a stream of tokens representing an arithmetic
expression (with numbers)
• valStk holds values
Output: the value of the expression
• Use $ as special “end of input” token with lowest
precedence
while there’s another token z
if isNumber(z) then
Algorithm doOp()
valStk.push(z)
x  valStk.pop();
y  valStk.pop(); else
op  opStk.pop(); repeatOps(z);
valStk.push( y op x ) opStk.push(z)
repeatOps($);
Algorithm repeatOps( refOp ): return valStk.top()
while ( valStk.size() > 1 
prec(refOp) ≤ prec(opStk.top() )
doOp()
Stallmann 2010 © 103

Algorithm on an
Example Expression
7 + 2 * 3 – 4 ≤ 14
Operator ≤ has lower
–/+ precedence than

4 –
14 ≤

3 *
$ $
4 –
7 $
14 ≤ F
+ 2- + 5
+ 14 ≤ 14 ≤
2 2
3 * 3 * 6
4 – 4 – 4 – 2- +
14 ≤ 14 ≤ 14 ≤ 14 ≤

You might also like