0% found this document useful (0 votes)
16 views

Lec2-Stack Using Arrays

sqs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Lec2-Stack Using Arrays

sqs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Data Structures

STACK USING ARRAYS


Learning outcome(s)

By the end of the lecture, the student can able to know

• Create and implement stack operations 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

• A stack can be implemented in two ways.


• Stack using Arrays
• Stack using Linked List
Stack using arrays
In stack, push and pop operations are performed from only one
end i.e top.
step2:
Procedure for push(): Let stack size=5 push 10
,top=-1
Step1: 4
4
3 3
2
2
1 1
0 0 10 top=0

top=-1
Stack using arrays

Step 3: push Step 4: push 30


20
4 4
3 3
2 2 30 top=2
1 20 top=1 1 20
0 10 0 10
Stack using arrays

step5: push 40 step6: push 50

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

Procedure for pop():


Step1: Step2: pop
50

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

Step3: pop Step4: pop


40 30

4 4
3 40 3
30 top=2
2 2 30
1 20 1 20 top=1
0 10 0 10
Stack using arrays

Step5: pop Step6: pop


20 10

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 void peak()


3 40
{
2 30
1 20 printf(“%d “,stack[top]);
0 10 }
Stack using arrays

Procedure for display():

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

Procedure for display():

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

Procedure for display():

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--)

50 40 30 20 10 printf(“ %d\t “, stack[i]);


}
www.slido.com

#57056
Thank you

You might also like