Data Structures and Algorithm (20IS6OEDSA) UNIT 2 It is an ordered group of homogeneous items of elements. Elements are added to and removed from the top of the stack (the most recently added items are at the top of the stack). The last
"Data Structures and Algorithm (20IS6OEDSA) UNIT 2" is the property of its rightful owner. Permission is granted to
download and print the materials on this website for personal, non-commercial use only, and to display it
on your personal computer provided you do not modify the materials and that you retain all copyright
notices contained in the materials. By downloading content from our website, you accept the terms of this
agreement.
Presentation Transcript
01
Data Structures and Algorithm (20IS6OEDSA)
UNIT 2<br>
02
It is an ordered group of homogeneous items of elements.
Elements are added to and removed from the top of the stack (the most recently added items are at the top of the stack).
The last element to be added is the first to be removed (LIFO: Last In, First Out). STACKS<br>
03
Stack Specification Definitions: (provided by the user)
MAX_ITEMS: Max number of items that might be on the stack
ItemType: Data type of the items on the stack
Operations
MakeEmpty
Boolean IsEmpty
Boolean IsFull
Push (ItemType newItem)
Pop (ItemType& item)<br>
04
Push (ItemType newItem) Function: Adds newItem to the top of the stack.
Preconditions: Stack has been initialized and is not full.
Postconditions: newItem is at the top of the stack.<br>
05
Pop (ItemType& item) Function: Removes topItem from stack and returns it in item.
Preconditions: Stack has been initialized and is not empty.
Postconditions: Top element has been removed from stack and item is a copy of the removed element.<br>
06
Stack Implementation #include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 5
// Global declarations
int s[MAX],top=-1;
void push();
void pop();
void display();<br>
07
Stack Implementation (cont.) void main()
{
int ch;
char str[30];
for(;;)
{
printf(" \n IMPLEMENTATION OF STACK OF INTEGERS USING ARRAY \n");
printf("\n 1 : PUSH \n 2 : POP \n 3 : Display \n
4: Exit \n");
printf("\n Enter your Choice : ");
scanf("%d“,&ch);
switch(ch)
{
case 1: push();
break; case 2:
pop();
break;
case 3:
display();
break;
default : exit(0);
}
}
}<br>
08
Stack Implementation (cont.) void push()
{
int item;
if(top==MAX-1)
printf("\n STACK OVERFLOW \n");
else
{
printf("\n Enter the Element : ");
scanf("%d",&item);
top=top+1;
s[top]=item;
}
}<br>
09
Stack Implementation (cont.) void pop()
{
int item;
if(top==-1)
printf("\n STACK UNDERFLOW \n");
else
{
item=s[top];
printf("\n The Deleted Element is %d\n",item);
top=top-1;
}
}<br>
10
Stack Implementation (cont.) void display()
{
int i;
if(top==-1)
printf("\n The Stack is Empty \n");
else
{
printf("\n The Elements present in Stack are \n ");
for(i=top;i>=0;i--)
printf("\t %d \n",s[i]);
}
}<br>