3.1.2 Stacks Array Implementation

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 11

Data Structures and

Algorithm Analysis I
(Unit III – Session 1 – Part 2)

Stacks – Array Implementation

Dr.G.Anupriya
Professor - CSE Department

CSE - Data Structures and Algorithm Analysis 1


Unit III – Course Outcome
• At the end of this unit, students will be able to:
Perform operations on Stack and Queue data structures for
various applications
• At the end of this session, students will be able to:
Implement operations on Array based Stacks

CSE - Data Structures and Algorithm Analysis 2


Stack
• Array Implementation
• Used for Static Stacks when array size is known in
advance
• Similar to array implementation of lists
• Top pointer or variable has to be maintained additionally
• Insert and Delete only at top end

3
Stack – Array Implementation
• Array Declaration
int MAX=5; 4
3
int top =-1; 2
1
int S[MAX]; 0
Top = -1
Empty Stack - S

4
Stack – Array Implementation
4
• Push operation Empty
Stack - S 3
void Push(int val) 2
{ Top = -1 1
0
if(top == MAX-1)
{
Push 1
printf(“Stack is Full”); return;
4
} 3
S[++top] = val; 2
} 1
Time Complexity – O(1) Top = 0 0 1

5
Stack – Array Implementation
Top = 4 4 9
• Push operation
3 7
void Push(int val) 2 5
{ 1 3
0 1
if(top == MAX-1)
{
Push 11
printf(“Stack is Full”); return;
Top = 4 4 9
} 3 7
S[++top] = val; 2 5
} Stack is Full 1 3
0 1

6
Stack – Array Implementation
Top = 4 4 9
• Pop operation
3 7
int Pop( ) 2 5
{ 1 3
if(top==-1) 0 1

{ printf(”Stack is Empty”);
Pop
return -1;
4
} Top = 3 3 7

else return S[top--]; 2 5

} 1 3
Time Complexity – O(1) 9 is returned
0 1

7
Stack – Array Implementation
4
• Pop operation
3
int Pop( ) 2
{ 1
if(top==-1) Top = -1 0

{ printf(”Stack is Empty”);
Pop
return -1;
4
} 3

else return S[top--]; 2

} 1
Stack is empty Top = -1 0

8
Stack – Array Implementation
4
• Top operation
Top = 3 3 7
int Top_val( ) 2 5
{ 1 3
if(top==-1) 0 1

{ printf(”Stack is Empty”);
Top
return -1;
4
} Top = 3 3 7

else return S[top]; 2 5

} Return 7 1 3
Time Complexity – O(1) No change in Top 0 1

9
Summary
Array implementation
Push, Pop and Top
Time Complexity – O(1)

CSE - Data Structures and Algorithm Analysis 10


References
• Mark A. Weiss, “Data Structures and Algorithm Analysis in
C”, Second Edition, Pearson Education, 2011.
• Anany Levitin, “Introduction to the Design & Analysis of
Algorithms”, Third Edition, Pearson Education, 2011.

CSE - Data Structures and Algorithm Analysis 11

You might also like