Está en la página 1de 16

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

1. Create Creates a new empty stack.


2. Push
Inserts a new element at top of the stack.
Top points to the new added element.
3. Pop
It removes the topmost element from the
stack
Stack size reduced by one.

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

Static stack using arrays


Dynamic stack using link list

5
Pictorial representation of static
stack
TOP E
TOP D E
D D
C
C C
B
B B
A
A A

INITIAL STACK PUSH E POP E

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

Note that IsFull operation is not necessary here!


11
Code
public class Node {
int data;
Node link;
}
Public Class Stack
{ Stack top
pointing to NULL
static Node top = null;
static int cnt = 0;
int emptystack() {
return (top == null); } Tests if the
stack is empty
12
Node push(Node newnode)
{
if(isEmpty())
{
top=newnode;
top.setLink(null);
cnt++;
}
else
{
newnode.setLink(top);
top=newnode;
cnt++;
}
newnode NULL
return top;

}
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

Write a program to accomplish this using stack.


17

También podría gustarte