Lec2-Stack Using Arrays
Lec2-Stack Using Arrays
link
Todays Concepts
• STACK ADT
• Implementation of stack
Stack adt
Data: top
Operations:
• push()- insert an element into the stack.
• pop()- removes an element from the stack.
• peak()-prints the top element from the stack.
• Display()-prints the contents of the stack.
• isFull()-to check whether the stack is full or not
• isEmpty()- to check whether the stack is empty or not
Stack implementation
top=-1
Stack using arrays
4 50 top=4
4
3 40
3 40 top=3
2 30
2 30
1 20
1 20
0 10
0 10
step7:push
60 top>= SIZE-1 OVERFLOW
4 50
3 40
30
2
1 20
0 10
Stack using arrays
void push()
if(top>=SIZE-1)
printf(“STACK OVERFLOW”);
else
printf(“Enter a value\n”);
scanf(“%d”,&x);
top++;
stack[top]=x;
}
Stack using arrays
4 50 top=4 4 50
3 40 3 40 top=3
2 30 2 30
1 20 1 20
0 10 0 10
Stack using arrays
4 4
3 40 3
30 top=2
2 2 30
1 20 1 20 top=1
0 10 0 10
Stack using arrays
4 4
3 3
2 2
1 20 1
0 10 top=0 0 10
top=-1
UNDERFLOW
Stack using arrays
void pop()
{
if(top==-1)
printf(“STACK UNDERFLOW”);
else
{
x=stack[top];
top--;
}
}
Stack using arrays
Procedure peak (): prints the top element from the stack
4 50 top=4 4 50
3 40 3 40 top=3
2 30 2 30
1 20 1 20
0 10 0 10
50 50 40
Stack using arrays
4 50 4 50
3 40 3 40
30 top=2 30
2 2
1 20 1 20 top=1
0 10 0 10
50 40 30 50 40 30 20
Stack using arrays
void display()
{
4 50 if(top==-1)
3 40 printf(“STACK EMPTY\n”);
2 30
1 20 printf(“stack contents are\
n”); 0 10 top=0
for(i=top;i>=0;i--)
#57056
Thank you