Professional Documents
Culture Documents
3 Stack
3 Stack
1
Stack
A stack is a list of data elements which inserts
an element at the end of the list, and deletes
an element from the same end.
No insertion or deletion from anywhere else is
allowed.
It is also called a LIFO (last in first out) list.
2
Operations on stack
The operations performed on stack are
3
Operations on stack
4. Isempty
Checks whether the stack is empty.
It returns true (1) if stack is empty else false
(0).
Used by pop operation.
5. Isfull
Checks whether the stack is full.
It returns true(1) if stack is full else false(0).
Used by push operation
4
Implementation of stack
Two ways of stack implementation are
5
Pictorial representation of static
stack
TOP E
TOP D E
D D
C
C C
B
B B
A
A A
6
Code
public class Stack {
{
final int SIZE = 5;
int top=0; Creates an array
int[] item = new int[SIZE]; representing stack
final int FUL=SIZE-1;
final int EMPTY = -1;
7
int pop(Stack s)
{
try
{
if(!isEmpty(s))
{
top=--s.top;
return s.item[top];
}
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println("underflow");
}
return EMPTY;
}
If the stack is not empty it pops the data from the
top of the list. 9
int isFull(stack s)
{
return (s.getTop() == FULL);Checks if the
} stack is full
boolean isEmpty(Stack s)
{ Checks if the
stack is empty
return (s.getTop()==EMPTY);
}
10
Pictorial representation of
dynamic (linked) stack
TOS TOS
D *
E * D *
E *
TOS C * D * C *
B *
C * B *
A *
B * A *
null
null A *
null
INITIAL STACK PUSH E POP E
}
NULL 13
top
Node pop()
{
Node temp = top;
if(isEmpty())
return null;
else if(top.getLink()==null)
{
top=null;
cnt--;
}
temp
NULL
top 14
else
{
top = top.getLink();
temp=null;
cnt--;
}
return top;
}
Application of stacks
Compilers
Applications like
parenthesis matching in an expression
Conversion between infix prefix &postfix
expressions
Recursion
Interrupt handling
16
Parenthesis Matching
((5+6)*9)
((5+6)
((
(
((5+6)*9)
( (
( ( ( (
null null null null