DATA STRUCTURES ( C++ )
Let us take an array a[5] and take a variable top points to -1.
PUSH:To INSERT the element in to stack using top.Here we check for the OVERFLOW condition.
POP:To RETRIEVE elements from the stack using top.Here we check for the UNDERFLOW condition.This concept is nothing but LIFO.
SOURCE CODE:
/* Program To Implement Stack using Array */
#include < iostream.h >
#include < conio.h >
#include < stdlib.h >
#define MAX 10
class stack
{
private : int sp, a [ MAX ];
public :
void init ( );
void push ( int );
void pop ( );
void display ( );
void count ( );
};
void stack :: init ( )
{
sp = – 1;
}
void stack :: push ( int data)
{
if (sp = = ( MAX – 1 ) )
{
cout<<« \n STACK OVERFLOW…….\n »;
return;
}
sp + + ;
a [ sp ] = data;
}
void stack :: pop ( )
{
if ( sp < 0 )
{
cout<<« \n STACK UNDERFLOW…..\n »;
return;
}
cout<<« \n POPED DATA IS ::: « <<a[sp];
sp – – ;
}
void stack :: display ( )
{
cout << « \n DATA PRESENT IN A STACK IS ::: \n »; for ( int i = sp ; i > = 0 ; i – -)
cout << a [ i ] <<« \t »;
}
void stack :: count ( )
{
cout<<« \n NUMBER OF ELEMENTS IN A STACK ARE ::: « <<(sp+1);
};
void main ( )
{
stack ob;
int data,ch;
clrscr ( );
ob.init ( );
cout<<« \n**********STACK OPERATIONS**********\n »;
cout<<« \n1.Push Operation »;
cout<<« \n2.Pop Operation »;
cout<<« \n3.Display Operation »;
cout<<« \n4.Count Operation »;
cout<<« \n5.Exit Operation »;
cout<<« \n*************************************\n »;
do
{
cout<<« \n ENTER YOUR CHOICE :: « ; cin>>ch;
switch ( ch )
{
case 1:cout<<« \n ENTER ELEMENT TO BE INSERTED ::: »; cin>>data;
ob.push ( data ); break;
case 2: ob.pop ( ); break;
case 3: ob.display ( ); break;
case 4:ob.count ( ); break;
case 5: exit ( 0 );
defualt: cout<<« \nINVALID CHOICE « ;
}
}
while ( ch ! = 5 );
getch ( );
}
STACK USING LINKED LIST
We will create a linked list and insert an element ‘10’ and address as ‘0’.using top for the first node.For second node insert data element ‘20’ and insert first node address at second node address field.For third node insert data element ‘30’ and insert second node address at third node address field . after thirty we will stop the process .If we want to print the elements 30,20,10 will be displayed, Thiss follows LIFO conceot.
Source code:
#include
#include
class st
{
public:
struct node
{
int data;
struct node *next;
}*start,*temp,*top;
st()
{
start=temp=top=NULL;
}
void create()
{
int d;
cout<<« Enter data »; cin>>d;
if(start==NULL)
{
start=new node;
start->data=d;
start->next=NULL;
top=start;
}
else
{
temp=new node;
temp->data=d;
temp->next=top;
top=temp;
}
}
void disp()
{
while(top!=NULL)
{
cout<data<<« \t »; top=top->next;
}
}
};
void main()
{
st ob;
int ch;
clrscr();
while(ch)
{
cout<<« Enter ur choice »;
cout<<« 0 STOP\n1 CREATE\n 2 READ »; cin>>ch;
if(ch==1)
ob.create();
else if(ch==2)
ob.disp();
}
}