The Stack Abstract Data Type A stack is an abstract data type ADT that supports two main methods: pusho: Inserts object o onto top of stack Input: Object; Output: none pop: Re
Trang 1Trần Thị Thanh Nga
ngattt@hcmuaf.edu.vn
Khoa Công nghệ thông tin, ĐH Nông Lâm HCM
Trang 2 Inserting an item is known as “pushing” onto the
stack “Popping” off the stack is synonymous with removing an item
Trang 3Stacks examples
Example 5.1: Internet Web browsers store the addresses
of recently visited sites on a stack
Each time a user visits a new site, that site's address is
"pushed" onto the stack of addresses
The browser then allows the user to "pop" back to
previously visited sites using the "back" button
Example 5.2: Text editors usually provide an "undo"
mechanism that cancels recent editing operations and
reverts to former states ofa document
This undo operation can be accomplished by keeping
text changes in a stack
Trang 4The 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 of stack and returns it; if
stack is empty an error occurs
Input: none;
Output: Object
Trang 5The Stack Abstract Data Type
There are other methods:
size(): Return the number of elements in the stack
Input: none; Output: integer;
isEmpty(): Return a Boolean indicating if the stack is
empty
Input: none; Output: boolean;
top(): Return the top element in the stack, without removing it; an error occurs if the stack is empty
Input: none; Output: Object;
clear(): Remove all items from the stack
Trang 6Stack example
Trang 7A Stack Interface in Java
Because of its importance, the stack data structure is
included as a "built-in" class in the java.util package of
Java But you can define it your own specific one
Implementing an abstract data type in Java involves two steps
the definition of a Java interface, which describes the names
of the methods that the ADT supports
how they are to be declared and used
Trang 8A Stack Interface in Java
In addition, we must define exceptions for any error
conditions that can arise
For example: the error condition that occurs when calling
method pop() or top() on an empty stack throwing an
exception of type EmptyStackException
public class EmptyStackException extends RuntimeException {
public EmptyStackException(String err ) {
super ( err );
}
}
Trang 9A Stack Interface in Java
public interface StackInterface<E> {
public int size();
public boolean isEmpty();
public E top() throws StackException;
public void push(E element );
public E pop() throws StackException;
public void clear();
}
Trang 10A Simple Array-Based Stack Implementation
The stack consists of:
an array A of a default size (≥ 1),
the variable top that refers to the top element in the
stack, top changes from -1 to capacity – 1
the capacity that refers to the array size
The stack is empty when top = -1, and the stack is full
when top = capacity-1
Trang 11A Simple Array-Based Stack Implementation
public class ArrayStack<T> implements
StackInterface<T> {
private static final int DEFAULT_CAPACITY = 15;
private int top ; //reference to the top element
A = (T[]) new Object[ initialCapacity ];
top = -1; // stack is empty }
Trang 12A Simple Array-Based Stack Implementation
public boolean isEmpty() {
return top == -1;
}
public void clear() {
for ( int i = 0; i <= top ; i ++)
Trang 13A Simple Array-Based Stack Implementation
Trang 14A Simple Array-Based Stack Implementation
public void push(T e ) {
Trang 15A drawback with ArrayStack
The array implementation of a stack is simple and
efficient but you have to asssume a fixed upper bound,
CAPACITY
If you chose the CAPACITY value 1,000 more or less
arbitrarily
An application may actually need much less space than this,
which would waste memory
An application may need more space than this, which would
cause our stack implementation to generate an exception as
soon as a client program tries to push its 1,001st object
on the stack
Trang 16Implementing a Stack with a
Generic Linked List
The top of the stack is 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
When we push a new element e on the stack, we simply
create a new node v for e, reference e from v, and insert v
at the head of the list
When we pop an element, simply remove the node at the
head of the list and return its element
We perform all insertions and removals of elements at the
head of the list
Trang 17Node class
public class Node<T> {
public T data ;
public Node<T> next ;
public Node(T data ) {
this ( data , null );
}
public Node(T data , Node<T> n ) {
this data = data ;
next = n;
}
}
Trang 18ListStack class
public class ListStack<T> implements Stack<T> {
private Node<T> top ;
protected int size ;
public ListStack() {
top = null ;
size = 0;
}
public boolean isEmpty() {
return top == null ;
}
public void clear() {
top = null ;
}
Trang 19public void push(T data ) {
top = new Node<T>( data , top );
}
Trang 20ListStack class
/**Removes and returns the item at the top*/
public T pop() {
if (isEmpty())
throw new StackException( "Stack is empty" );
T data = top data ;
top = top next ;
return data ;
}
Trang 21ListStack class
/**Returns the top item without its removal*/
public T peek() {
if (isEmpty())
throw new StackException( "Stack is empty" );
return top data ;
}
Trang 22Application of Stacks
Postfix Expressions Calculator
Converting a Number from Decimal to Binary
Trang 231 Postfix Expressions Calculator
The usual notation for writing arithmetic expressions (the
notation we learned in elementary school) is called infix
notation, in which the operator is written between
the operands, for example: a + b
In the early 1920s, the Polish mathematician Jan
Lukasiewicz discovered that if operators were written
before the operands (prefix or Polish notation; for
example, + a b), the parentheses can be omitted
Trang 241 Postfix Expressions Calculator
In the late 1950s, the Australian philosopher and early
computer scientist Charles L Hamblin proposed a scheme
in which the operators follow the operands (postfix
operators), resulting in the Reverse Polish notation
This has the advantage that the operators appear in the order required for computation
For example:
the expression: a + b * c
in a postfix expression is: a b c * +
Trang 251 Postfix Expressions Calculator
Trang 261 Postfix Expressions Calculator
Trang 27Converting from Infix to Postfix
1 Read in the tokens one at a time
2 If a token is an integer, write it into the output
3 If a token is an operator, push it to the stack, if the stack is
empty If the stack is not empty, you pop entries with higher
or equal priority and only then you push that token to the stack
4 If a token is a left parentheses '(', push it to the stack
5 If a token is a right parentheses ')', you pop entries until you
meet '('
6 When you finish reading the string, you pop up all tokens
which are left there
7 Arithmetic precedence is in increasing order: '+', '-', '*', '/';
Trang 28Converting from Infix to Postfix
Infix: 2+(4+3*2+1)/3
Trang 29Evaluating a Postfix Expression
Postfix expressions can be evaluated using the following
algorithm:
Scan the expression from left to right
When an operator is found, back up to get the required
number of operands, perform the operation, and continue
Trang 30Evaluating a Postfix Expression
5 9 3 + 4 2 * * 7 + *
Trang 31Evaluating a Postfix Expression
Trang 32Push 5
Push 6
Read -
Pop 6, Pop 5, Push -1
Read -
Pop -1, Pop 7, Push 8
Read *
Pop 8, Pop 2, Push 16
3 + 4 = 7
5 - 6 = -1
7 - -1 = 8
2 * 8 = 16
Trang 332 Converting a Number from
Trang 34while (n!= 0) {
r= n % 2;
push (s, r); // push so du vao stack
n = n/2;
} System.out.print("Kết quả: “);
while (!isEmpty(s)) System.out.println(pop(s)); // pop so du ra khoi stack
2 Converting a Number from Decimal
to Binary
Trang 35Quick Review
A stack is a data structure in which the items are added
and deleted from one end only
A stack is a Last In First Out (LIFO) data structure
The basic operations on a stack are as follows:
Push an item onto the stack, pop an item from the stack, retrieve the top element of the stack, initialize the stack, check whether the stack is empty, and check whether the stack is full
A stack can be implemented as an array or a linked list
The middle elements of a stack should not be accessed directly
Trang 36Quick Review
Stacks are restricted versions of arrays and linked lists
Postfix notation does not require the use of parentheses to
enforce operator precedence
In postfix notation, the operators are written after the
operands
Postfix expressions are evaluated according to the
following rules:
Scan the expression from left to right
If an operator is found, back up to get the required number
of operands, evaluate the operator, and continue
Trang 37Question?