Semester Genap 2010/2011: Beni Suranto, ST
Semester Genap 2010/2011: Beni Suranto, ST
• Applications of Stack.
What is a Stack?
• Stack is a data structure in which data is added and removed at only one
end called the top.
• To add (push) an item to the stack, it must be placed on the top of the
stack.
• To remove (pop) an item from the stack, it must be removed from the top
of the stack too.
• Thus, the last element that is pushed into the stack, is the first element to
be popped out of the stack.
i.e., Last In First Out (LIFO)
An Example of Stack
top 2
top 8 8
top 1 1 1
Push(8) Push(2)
7 7 7
2 2 2
pop()
top 8
top 1
1
top 7 7 pop()
pop() 7
2 2
2
Stack Implementations
• Two implementations:
– StackAsArray
• The underlying data structure is an array of Object
– StackAsLinkedList
• The underlying data structure is an object of MyLinkedList
StackAsArray – Constructor
// …
StackAsArray – empty() Method
• To empty the stack, the purge method simply assigns the value null to the
first count positions of the array.
• The pop method removes an item from the stack and returns that item.
• The pop method first checks if the stack is empty. If the stack is empty, it
throws a ContainerEmptyException. Otherwise, it simply decreases count
by one and returns the item found at the top of the stack.
public StackAsLinkedList(){
list = new MyLinkedList();
}
// …
StackAsLinkedList Implementation
public void push(Object obj){
list.prepend(obj);
count++;
}
(5+9)*2+6*5
• An ordinary arithmetical expression like the above is called infix-expression -
- binary operators appear in between their operands.
Infix Postfix
16 / 2 16 2 /
(2 + 14)* 5 2 14 + 5 *
2 + 14 * 5 2 14 5 * +
(6 – 2) * (5 + 4) 6 2 - 5 4 +*
Application of Stack :
Evaluating Postfix Expression
• The following algorithm uses a stack to evaluate a postfix expressions.