Professional Documents
Culture Documents
3.1.2 Stacks Array Implementation
3.1.2 Stacks Array Implementation
3.1.2 Stacks Array Implementation
Algorithm Analysis I
(Unit III – Session 1 – Part 2)
Dr.G.Anupriya
Professor - CSE Department
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
} 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
} 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
} 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)