SlideShare a Scribd company logo
DATA STRUCTURES ( C++ ) 
DATASTRUCTURES PROGRAMMING CONCEPTS 
Developed by, 
M.V.B.REDDY,CSE 
Associate professor, 
Dept. of CSE, GST, 
GITAM UNIVERSITY. 
Email ID : bramhareddy999@gmail.com
 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. 
STACK USING ARRAYS 
 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 ( ) 
{i 
f ( 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 ( ); 
}
OUTPUT:
 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 
STACK node address USING field. 
LINKED LIST 
 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<conio.h> 
#include<iostream.h> 
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<<top->data<<"t"; 
top=top->next; 
} 
} }; 
void main() 
{ 
st ob; 
int ch; 
clrscr();
while(ch) 
{ 
cout<<"Enter ur choice"; 
cout<<"0 STOPn1 CREATEn 2 READ"; 
cin>>ch; 
if(ch==1) 
ob.create(); 
else if(ch==2) 
ob.disp(); 
} 
} 
OUTPUT:
 Here we will take an array a[5],and two variables front, rear points to -1. 
 WRITE: 
QUEUE USING ARRAYS 
 Here will insert the element into the queue using rear variable. 
 Here check for the Overflow condition. 
 READ: 
 Here we will retrieve the elements from the queue using front variable. 
 Here check for the Underflow condition. 
 This follows the FIFO concept. 
rear 
-1 0 1 2 3 4 
front
SOURCE CODE: 
/* Program To Implement Queue using Array */ 
#include< iostream.h > 
#include< conio.h > 
#include< process.h > 
#define MAX 10 
class queue 
{ 
private : int front, rear, a [ MAX ]; 
public : 
void init ( ); 
void write ( int ); 
void read ( ); 
void count ( ); 
void display ( ); 
}; 
void queue :: init ( ) 
{f 
ront = rear = - 1; 
} 
void queue :: write ( int data) 
{ if ( rear = = ( MAX - 1 ) ) 
cout<<"n QUEUE IS OVERFLOW......"; 
else 
a [ + + rear ] = data; 
} 
void queue :: read ( ) 
{ if( front = = rear ) 
cout<<"n QUEUE IS UNDERFLOW....."; 
else 
cout<<"n DELETED ELEMENT IN QUEUE IS :: "<<a[++front]; 
}
void queue :: count ( ) 
{ 
cout<<"n NUMBER OF ELEMENTS IN A QUEUE ARE :: 
"<<(rear-front); 
} 
void queue :: display ( ) 
{ 
cout<<"n ELEMENTS IN A QUEUE ARE:: "; 
for( int i = (front + 1); i < = rear; i + + ) 
cout<< a [ i ]<<"t"; 
} 
void main ( ) 
{ 
queue ob; 
int ch,data; 
clrscr ( ); 
ob.init ( ); 
cout<<"n*****QUEUE OPERATIONS****n"; 
cout<<"n1.Write "; 
cout<<"n2.Read "; 
cout<<"n3.Count"; 
cout<<"n4.Display"; 
cout<<"n5.Exit"; 
cout<<"**************************n";
do 
{ 
cout<<"n ENTER YOUR CHOICE :: "; 
cin>>ch; 
switch ( ch ) 
{ 
case 1:cout<<"n ENTER ELEMENT TO BE INSERTED IN QUEUE :: "; 
cin>>data; 
ob.write ( data ); 
break; 
case 2:ob.read ( ); 
break; 
case 3:ob.count ( ); 
break; 
case 4:ob.display ( ); 
break; 
case 5:exit ( 0 ); 
break; 
default :cout<<"n INVALID CHOICE..."; 
}} 
while( ch ! = 5 ); 
getch ( ); 
}
OUTPUT:
 Here we will create linked list with ‘n’ nodes one after another 10,20,30 etc. 
 If we try to print the elements it will display as 10,20,30. which follows FIFO 
Queue concept. 
using linked list
SOURCE CODE: 
/* Program To Implement Queue using Linked List */ 
#include < iostream.h > 
#include< conio.h > 
#include < alloc.h > 
#define NULL 0 
class node 
{i 
nt data; 
node *next; 
public: 
void create ( node *); 
void print ( node *); 
}; 
void node :: create (node *list) 
{ 
cout<<"n ENTER THE INPUT NO :: "; 
cout<<"n TYPE 999 AT THE END :: "; 
cin>>list->data; 
if(list -> data = = 999) 
list->next = NULL; 
else 
{l 
ist -> next = new node; 
create( list -> next); 
} return; 
}
void node :: print (node *list) 
{i 
f( list -> next ! = 0) 
{ 
cout<< list->data; 
cout<<"->"; 
} 
else 
return; 
print( list -> next); 
} 
void main ( ) 
{ 
node *head, ob; 
clrscr ( ); 
head = new node; 
ob.create ( head ); 
cout<<"n QUEUE ELEMENTS ARE:: "; 
ob.print( head ); 
cout<<"999"; 
getch ( ); 
}
OUTPUT:
 A binary tree is a tree data structure in which each node has at most two children. Typically 
the child nodes are called left and right. Binary trees are commonly used to implement binary 
search trees and binary heaps. 
 Starting at the root of a binary tree, there are three main steps that can be performed and the 
order in which they are performed define the traversal type. 
BINARY TREE USING RECURSION 
 There are 3 types of traversals: 
 1. Pre-Order 
 2. In-Order 
 3. Post-Order 
 To traverse a non-empty binary tree in preorder, perform the following operations 
recursively at each node, starting with the root node: 
1. Visit the root. 
2. Traverse the left sub tree. 
3. Traverse the right sub tree. 
 To traverse a non-empty binary tree in in order, perform the following operations recursively 
at each node, starting with the root node: 
1. Traverse the left sub tree. 
2. Visit the root. 
3. Traverse the right sub tree. 
 To traverse a non-empty binary tree in post order, perform the following operations 
recursively at each node, starting with the root node: 
1. Traverse the left sub tree. 
2. Traverse the right sub tree. 
3. Visit the root.
15 
7 22 
BINARY TREE: 
Preorder:- 15,7,22 will be displayed . 
Post order:- 7,22,15 will be displayed . 
In order:- 7,15,22 will be displayed .
SOURCE CODE: 
/* Program To Implement Binary Tree Traversing */ 
#include < iostream.h > 
#include < conio.h > 
class bstree 
{ 
public: 
struct node 
{ 
int data; 
node *left; 
node *right; 
}*head; 
void create (node *); 
void inorder (node *); 
void preorder (node *); 
void postorder (node *); 
}; 
void* bstree:: create(node *list) 
{ 
node *temp1,*temp2; 
int val; 
if(list = = NULL) 
{ 
list = new node; 
cout<<"nEnter Data Element:: "; 
cin>>list->data; 
list -> left = list -> right = NULL; 
} 
else
{ 
cout<<"n enter the data element"; 
cin>>val; 
temp1 = list; 
while( temp1 ! = NULL ) 
{ 
temp2 = temp1; 
if(temp1 -> data > val) 
temp1 = temp1 -> left; 
else 
temp1 = temp1 -> right; 
} 
if(temp2 -> data > val) 
{ 
temp2 -> left = new node; 
temp2 = temp2 -> left; 
temp2 -> data = val; 
temp2 -> left = temp2 -> right = NULL; 
} 
else 
{ 
temp2 -> right = new node; 
temp2 = temp2 -> right; 
temp2 -> data = val; 
temp2 -> left = temp2 -> right = NULL; 
} 
} 
return (list); 
}
void bstree:: inorder(node *root) 
{ 
if( ! root ) 
return; 
inorder( root -> left ); 
cout<<root->data<<"t"; 
inorder( root -> right ); 
} 
void bstree::preorder(node*root) 
{ 
if( ! root ) 
return; 
cout<<root->data<<”t”; 
preorder( root -> left ); 
preorder( root -> right); 
} 
void bstree::postorder(node*root) 
{ 
if( ! root) 
return; 
postorder( root -> left ); 
postorder( root -> right ); 
cout<<root->data<<”t”; 
}
void main ( ) 
{ 
node n,*head; 
head = NULL; 
clrscr ( ); 
cout<<"nCreate A Binary Treen"; 
head=n.create ( head ); 
cout<<"n the inorder traversal gives the 
following nodes"; 
n.inorder ( head ); 
getch ( ); 
} 
OUTPUT:
BINARY SEARCH TREE 
15 
7 22 
A tree having left child less than parent and right child grater than the parent. 
Traversals are same as binary tree.
SOURCE CODE: 
/* Program to implement Binary search tree */ 
#include < iostream.h > 
#include < conio.h > 
class btree 
{ 
private : 
struct btreenode 
{ 
btreenode *leftchild ; 
int data ; 
btreenode *rightchild ; 
} *root; 
public: 
btree ( ) ; 
void buildtree ( int num ) ; 
static void insert ( btreenode **sr, int num ) ; 
void traverse ( ) ; 
static void inorder ( btreenode *sr ) ; 
static void preorder ( btreenode *sr ) ; 
static void postorder ( btreenode *sr ) ; 
static void del ( btreenode *sr ) ; 
~btree ( ) ; 
} ;
btree :: btree ( ) 
{ 
root = NULL ; 
} 
void btree :: buildtree ( int num ) 
{ 
insert ( &root, num ) ; 
} 
void btree :: insert ( btreenode **sr, int num ) 
{ 
if ( *sr == NULL ) 
{ 
*sr = new btreenode ; 
( *sr ) -> leftchild = NULL ; 
( *sr ) -> data = num ; 
( *sr ) -> rightchild = NULL ; 
return ; 
} 
else // search the node to which new node will be attached 
{ 
// if new data is less, traverse to left 
if ( num < ( *sr ) -> data ) 
insert ( & ( ( *sr ) -> leftchild ), num ) ; 
else 
// else traverse to right 
insert ( & ( ( *sr ) -> rightchild ), num ) ; 
}r 
eturn ; 
}
void btree :: traverse( ) 
{ 
cout << "nIN - ORDER TRAVERSAL :: " ; 
inorder ( root ) ; 
cout << "nPRE - ORDER TRAVERSAL :: " ; 
preorder ( root ) ; 
cout << "nPOST - ORDER TRAVERSAL :: " ; 
postorder ( root ) ; 
} 
void btree :: inorder ( btreenode *sr ) 
{ 
if ( sr != NULL ) 
{ 
inorder ( sr -> leftchild ) ; 
cout << "t" << sr -> data ; 
inorder ( sr -> rightchild ) ; 
} 
else 
return ; 
} 
void btree :: preorder ( btreenode *sr ) 
{ 
if ( sr != NULL ) 
{ 
// print the data of a node 
cout << "t" << sr -> data ; 
// traverse till leftchild is not NULL 
preorder ( sr -> leftchild ) ; 
// traverse till rightchild is not NULL 
preorder ( sr -> rightchild ) ; 
}
else 
return ; 
} 
void btree :: postorder ( btreenode *sr ) 
{ 
if ( sr != NULL ) 
{ 
postorder ( sr -> leftchild ) ; 
postorder ( sr -> rightchild ) ; 
cout << "t" << sr -> data ; 
} 
else 
return ; 
} 
btree :: ~btree( ) 
{ 
del ( root ) ; 
} 
void btree :: del ( btreenode *sr ) 
{ 
if ( sr != NULL ) 
{ 
del ( sr -> leftchild ) ; 
del ( sr -> rightchild ) ; 
} 
delete sr ; 
}
void main( ) 
{ 
btree bt ; 
int req, i = 1, num ; 
clrscr(); 
cout << "n SPECIFY THE NUMBER OF ITEMS TO BE INSERTED :: " ; 
cin >> req ; 
while ( i + + <= req ) 
{ 
cout << "n ENTER THE DATA :: " ; 
cin >> num ; 
bt.buildtree ( num ) ; 
} 
bt.traverse( ) ; 
getch(); 
} 
OUTPUT:
SPARSE MATRIX 
AIM: Write a program in C++ to implement ADDITION and MULTIPLICTION of two SPARSE 
matrixes. 
THEORY: 
If a lot of elements from a matrix have a value 0 then the matrix is known as 
SPARSE MATRIX. If the matrix is sparse we must consider an alternate way of representing it 
rather the normal row major or column major arrangement. This is because if majority of elements 
of the matrix are 0 then an alternative through which we can store only the non-zero elements and 
keep intact the functionality of the matrix can save a lot of memory space. 
Example: 
Sparse matrix of dimension 7 x 7. 
COLUMNS 
0 1 2 3 4 5 6 
0 0 0 0 -5 0 0 0 
1 0 4 0 0 0 0 7 
2 0 0 0 0 9 0 0 
ROWS 3 0 3 0 2 0 0 0 
4 1 0 2 0 0 0 0 
5 0 0 0 0 0 0 0 
6 0 0 8 0 0 0 0
SOURCE CODE: 
/*Program to demonstrate addition and multiplication of Two Sparse Matrix */ 
#include < iostream.h > 
#include < conio.h > 
#define x 25 
class sparce 
{ 
private: 
int a [ x ] [ x ], b [ x ] [ x ], c [ x ] [ x ], m, n, p, q; 
public: 
void init ( ); 
void input ( ); 
void add ( ); 
void mul ( ); 
void display ( int [25][25], int, int ); 
void convert( int [25][25], int, int ); 
}; 
void sparce :: init ( ) 
{ 
int i, j; 
for(i = 0; i < x;i + + ) 
for( j = 0; j < x; j + +) 
c [ i ] [ j ] = 0; 
}
void sparce :: input() 
{ 
int i,j; 
cout<<"nEnter order Of First matrix::"; 
cin>>m>>n; 
cout<<"nEnter order Of Second matrix::"; 
cin>>p>>q; 
cout<<"nEnter"<<m*n<<"Elements Into First Matrixn"; 
for(i=0;i<m;i++) 
for( j = 0; j < n; j + + ) 
cin>> a[ i ] [ j ]; 
cout<<"nEnter"<<p*q<<"Elements Into Second Matrixn"; 
for(i = 0; i < p ; i + + ) 
for ( j = 0; j < q ; j + + ) 
cin>>b [ i ] [ j ]; 
} 
void sparce :: add ( ) 
{ 
int i, j; 
if( m = = p && n = = q ) 
{ 
for( i = 0 ; i < m ; i + + ) 
for( j = 0; j < n; j + + ) 
c[ i ] [ j ] = a [ i ][ j ] + b [ i ] [ j ]; 
convert( c, m, n); 
} 
else 
cout<<"nAddition Is Not Possible"; 
}
void sparce :: mul ( ) 
{ 
int i, j, k; 
if(n = = p) 
{ 
for( i = 0; i < m; i + +) 
for( j = 0; j < q; j + + ) 
for( k = 0; k < n; k + + ) 
c[ I ] [ j ] + = a [ I ] [ k ] * b [ k ] [ j ]; 
convert(c, m, n); 
} 
else 
cout<<"n Multiplecation Is Not Possible"; 
} 
void sparce :: display(int c[25][25], int m, int n) 
{ 
int i,j; 
for( i = 0 ;i < m; i + + ) 
{ 
for( j = 0 ; j < n ; j + + ) 
cout<<c [ i ] [ j ]<<"t"; 
cout<<"n"; 
} 
}
void sparce :: convert(int c[25][25], int m, int n) 
{ 
int i, j, k = 1,t = 0; 
int sp[25][25]; 
for( i = 0 ; i < m ; i + +) 
for( j = 0 ; j < n ; j + + ) 
if(c [ i ] [ j ] ! = 0 ) 
{ 
sp [ k ] [ 0 ] = i; 
sp [ k ] [ 1 ] = j; 
sp [ k ] [ 2 ] = c [ i ] [ j ]; 
k + + ; 
t + + ; 
} 
sp[ 0 ] [ 0 ] = m; 
sp[ 0 ] [ 1 ] = n; 
sp[ 0 ] [ 2 ] = t; 
display( sp, k, 3); 
} 
void main ( ) 
{ 
sparce ob; 
clrscr ( ); 
ob.init ( ); 
ob.input ( ); 
cout<<"nAddition of Two Sparce Matrixn"; 
ob.add ( ); 
ob.init ( ); 
cout<<"nMultiplecation Of Two Sparce Matrixn"; 
ob.mul ( ); 
getch ( ); 
}
OUTPUT:
INFIX TO POSTFIX CONVERTIONic 
 Suppose Q is an arithmetic expression written in infix notation. This algorithm finds the 
equivalent postfix expression P. 
 Step 1. Push “(“ onto stack and add “)” to the end of Q. 
 2. Scan Q from left to right and repeat step 3 to 6 for each element of Q until the 
stack is empty. 
 3. If an operand is encountered , add it to p. 
 4. If a left parenthesis is encountered ,push it onto stack. 
 5 If an operator * is encountered , then: 
a. repeatedly pop from stack and top each operator (on the top of stack ) which 
has the same precedence or higher precedence than * . 
b. Add * to stack. 
 6. If a right parenthesis is encountered , then: 
a. repeatedly from stack and add to P each operator (on the top of stack) until a left 
parenthesis is encountered. 
b. remove the left parenthesis [ Do not add the left parenthesis top] [End of if 
structure] [End of step 2 loop] 
 7. Exit
Symbol scanned stack Expression P 
1 A ( A 
2 + ( + A 
3 ( ( + ( A 
4 B ( + ( AB 
5 * ( + ( * AB 
6 C ( + ( * ABC 
7 - ( + ( - ABC* 
8 ( ( + ( - ( ABC* 
9 D ( + ( - ( ABC*D 
10 / ( + ( - ( / ABC*D 
11 E ( + ( - ( / ABC*DE 
12 ^ ( + ( - ( / ^ ABC*DE 
13 F ( + ( - ( / ^ ABC*DEF 
14 ) ( + ( - ABC*DEF^/ 
15 * ( + ( - * ABC*DEF^/ 
16 G ( + ( - * ABC*DEF^/G 
17 ) ( + ABC*DEF^/G*- 
18 * ( + * ABC*DEF^/G*- 
19 H ( + * ABC*DEF^/G*-H 
20 ) ABC*DEF^/G*-H*+ 
(A+(B*C-(D/E^F)*G)*H)
SOURCE CODE: 
/* Program To implement infix to postfix Expression */ 
#include < iostream.h > 
#include< process.h > 
#include < conio.h > 
char stack[30], postfix[30], infix[30]; 
int top = - 1; 
int pri( char x ) 
{i 
nt value; 
switch ( x ) 
{ 
case ')': value=0; break; 
case '+': case '-': value=1; break; 
case '*': case '/': case '%': value=2; break; 
case '^': value=3; break; 
case '(': value=4; break; 
default: cout<<"INVALID EXPRESSION !!!!!!"; 
exit(1); 
} return value; 
}
void push ( char x ) 
{ 
top = top + 1; 
stack [top] = x; 
} 
char stacktop ( ) 
{ 
return stack [ top ]; 
} 
int isalnum (char x) 
{ 
return ( (x>='0' && x<='9') ||( x>='a' && 
x<='z') || ( x>='A' && x<='Z')); 
} 
char pop( ) 
{ 
return stack[top - - ]; 
}
void intopost(char infix[ ], char postfix[ ]) 
{ int i, j=0; 
char c, pc; 
for ( i = 0; ( c = infix[ i ] ) != '0' ; i + +) 
{ if ( isalnum (c) ) 
postfix [ j + + ] = c; 
else 
{ 
while ( top ! = - 1 && (pri (stacktop () ) >= pri (c) ) ) 
{ 
If ( stacktop( ) = = '(' && c! = ')' ) 
break; 
if ( stacktop( ) = = '(' && c = =')' ) 
{ 
pop () ; 
break; 
} 
pc = pop( ); 
if ( pc! = '(' ) 
postfix [ j + + ] = pc; 
else break; 
} 
if( c! = ')' ) 
push ( c ); 
}} while( top ! = -1 ) 
postfix[ j + + ] = pop( ); 
postfix [ j ] = '0'; 
}
void main ( ) 
{ 
clrscr ( ); 
cout<<"ENTER INFIX EXPRESSION ::nnttt"; 
cin>>infix; 
intopost( infix, postfix ); 
cout<<"POSTFIX EXPRESSION ::nnttt "; 
cout<<postfix; 
getch ( ); 
} 
OUTPUT:
POSTFIX EVALUATION 
THEORY: 
Reverse Polish notation is a mathematical notation wherein every operator 
follows all of its operands. It is also known as Postfix notation and is parenthesis free. 
In Reverse Polish notation the operators follow their operands; for instance, to add three 
and four, one would write “3 4 +” rather than “3 + 4”. If there are multiple operations, the operator 
is given immediately after its second operand; so the expression written “3 − 4 + 5” in 
conventional infix notation would be written “3 4 − 5 +” in RPN: first subtract 4 from 3, then add 5 
to that. 
Infix Expression: Any expression in the standard form like "2*3-4/5" is an Infix(In order) 
expression. 
Postfix Expression: The Postfix(Post order) form of the above expression is "23*45/-". 
Postfix Evaluation: In normal algebra we use the infix notation like a+b*c. The 
corresponding postfix notation is abc*+. The algorithm for the conversion is as follows: 
•Scan the Postfix string from left to right. 
•Initialize an empty stack. 
•If the scanned character is an operand, add it to the stack. If the scanned character is an 
operator, there will be at least two operands in the stack 
If the scanned character is an Operator, then we store the top most element of the 
stack(topStack) in a variable temp. Pop the stack. Now evaluate 
topStack(Operator)temp. Let the result of this operation be retVal. Pop the stack and 
Push retVal into the stack. 
Repeat this step till all the characters are scanned. 
•After all characters are scanned, we will have only one element in the stack. Return 
topStack.
Example: 
Postfix String: 1 2 3 * + 4 - . 
Initially the Stack is empty. Now, the first three characters scanned are 1,2 and 3, which are 
operands. Thus they will be pushed into the stack in that order. 
Stack Expression 
Next character scanned is "*", which is an operator. Thus, we pop the top two elements from the 
stack and perform the "*" operation with the two operands. The second operand will be the first 
element that is popped. 
Stack Expression 
The value of the expression(2*3) that has been evaluated(6) is pushed into the stack. 
Stack Expression
Next character scanned is "+", which is an operator. Thus, we pop the top two elements from the 
stack and perform the "+" operation with the two operands. The second operand will be the first 
element that is popped. 
Stack Expression 
The value of the expression(1+6) that has been evaluated(7) is pushed into the stack. 
Stack Expression 
Next character scanned is "4", which is added to the stack. 
Stack Expression 
Next character scanned is "-", which is an operator. Thus, we pop the top two elements from the 
stack and perform the "-" operation with the two operands. The second operand will be the first 
element that is popped.
The value of the expression(7-4) that has been evaluated(3) is pushed into the stack. 
Stack Expression 
The value of the expression(7-4) that has been evaluated(3) is pushed into the stack. 
Stack Expression 
Now, since all the characters are scanned, the remaining element in the stack (there will be only one End result: 
Postfix String : 1 2 3 * + 4 - 
Result : 3
SOURCE CODE: 
/*Program To Evaluate Postfix Expression */ 
#include < iostream.h > 
#include < conio.h > 
#include < math.h > 
#include < string.h > 
class postfix 
{ private: 
int stack[50], len, top; 
char post[50]; 
public: 
postfix ( ); 
void push ( int ); 
int pop ( ); 
int pfix ( ); 
}; 
void postfix :: postfix ( ) 
{ 
top = - 1; 
}i 
nt postfix :: pfix ( ) 
{ 
int a, b, i, temp; 
cout<<"nEnter Postfix Expression::"; 
cin>>post; 
len = strlen ( post ); 
post [ len] = '#';
for( i = 0 ; post [ i ] ! = '#' ; i + +) 
{ 
if( post [ i ] <= '9' && post [ i ] >= '0') 
push( post [ i ] - 48); 
else 
{ 
a = pop ( ); 
b = pop ( ); 
switch ( post [ i ]) 
{ 
case '+': temp = b + a; break; 
case '-': temp = b 
- a; break; 
case '*': temp = b * a; break; 
case '/': temp = 
b/a; break; 
case '%': temp = 
b%a; break; 
case '^': temp = 
pow( b, a ); 
} 
push ( temp ); 
} 
} 
return( pop ( ) ); 
}
void postfix :: push( int x ) 
{ 
stack[ + + top ] = x; 
}i 
nt postfix :: pop ( ) 
{ 
int x = stack [ top ]; 
top- -; 
return x; 
} 
void main ( ) 
{ 
int x; 
postfix ob; 
clrscr ( ); 
x=ob.pfix ( ); 
cout<<"nResult Of Postfix Expression Ist"<<x; 
getch ( ); 
} 
OUTPUT:
Quick Sort 
11 7 21 3 46 89 2 34 
right 
1)When pivot is at left end, 
1)Compare a[pivot] with a[right] element 
if (a[pivot] < a[right]) then right-- 
else 
swap a[pivot] and a[right] 
2)When pivot is at right end, 
Compare a[pivot] with a[left] element 
if (a[left] < a[pivot]) then left++ 
else 
swap a[left] and a[pivot] 
pivot 
left
STEP1: 11 7 21 3 46 89 2 34 
left, pivot right 
STEP2: 2 7 21 3 46 89 11 34 
left right, pivot 
STEP3: 2 7 21 3 46 89 11 34 
left right, pivot 
STEP4: 2 7 21 3 46 89 11 34 
left right, pivot 
STEP5: 2 7 11 3 46 89 21 34 
left, pivot right 
STEP6: 2 7 11 3 46 89 21 34 
left, pivot right
STEP7: 2 7 11 3 46 89 21 34 
left, pivot right 
STEP8: 2 7 11 3 46 89 21 34 
left, pivot right 
STEP9: 2 7 3 11 46 89 21 34 
left right, pivot 
STEP10: 2 7 3 11 46 89 21 34 
left, right, pivot 
 Here we will stop the main process as the left and right pointers are equal. 
 Now see the elements left to ‘11’ are less than ‘11’ and elements right to ‘11’ are grater than ‘11’. 
 Now divide the main list into 2 sub lists such as(2,7,3) and (46,89,21,34) and do the same above 
process.
 #include<stdio.h> 
#include<conio.h> 
#define MAXSIZE 500 
Source code 
void quickSort(int elements[], int maxsize); 
void sort(int elements[], int left, int right); 
int elements[MAXSIZE]; 
int main() 
{ int i, maxsize; 
printf(“nHow many elements you want to sort: “); 
scanf(“%d”,&maxsize); 
printf(“nEnter the values one by one: “); 
for (i = 0; i < maxsize; i++) 
{ 
printf (“nEnter element %i :”,i); 
scanf(“%d”,&elements[i]); 
}
printf(“nArray before sorting:n”); 
for (i = 0; i < maxsize; i++) 
printf(“[%i], “,elements[i]); 
printf (“n”); 
quickSort(elements, maxsize); 
printf(“nArray after sorting:n”); 
for (i = 0; i < maxsize; i++) 
printf(“[%i], “, elements[i]); 
} 
void quickSort(int elements[], int maxsize) 
{ 
sort(elements, 0, maxsize - 1); 
} 
void sort(int elements[], int left, int right) 
{ 
int pivot, l, r; 
l = left; 
r = right; 
pivot = elements[left]; 
while (left < right) 
{ 
while ((elements[right] >= pivot) && (left < right)) 
right—;
if (left != right) 
{ 
elements[left] = elements[right]; 
left++; 
} 
while ((elements[left] <= pivot) && (left < right)) 
left++; 
if (left != right) 
{ 
elements[right] = elements[left]; 
right—; 
}} 
elements[left] = pivot; 
pivot = left; 
left = l; 
right = r; 
if (left < pivot) 
sort(elements, left, pivot - 1); 
if (right > pivot) 
sort(elements, pivot + 1, right); 
}
 Consider the elements as shown, 
77 33 44 11 88 22 66 55 
77 0 
Selection sort 
min i 
 Here min is compared with a[1] 
 as min is > a[1] 
 min=a[1] 
33 0 
min i 
 This min is compared with a[2] ,as this is < a[2] 
 min is same that is 33 
 This min is compared with a[3] ,as this is > a[3] 
 min =a[3]. 
11 0 
min I 
 Now this is compared with a[4],a[5],a[6],a[7] as min is less than all of these min 
remains 33 
 At last swap min and a[i] like this continue the process with i=1,2,3……
SOURCE CODE: 
#include < iostream.h > 
#include < conio.h > 
class selsort 
{public : void sort(int *, int); 
}; 
void selsort::sort(int *a, int n) 
{ 
int i, j, x, min, temp; 
for( i = 0 ; i < ( n – 1 ) ; i + + ) 
{ 
x = i; min = a [ i ]; 
for( j = i + 1; j < n; j + + ) 
{i 
f( min > a [ j ] ) 
{ 
min = a [ j ]; 
x = j; 
}} temp = a [ i ] ; a [ i ] = a [ x ]; a [ x ] = temp; 
}} 
void main( ) 
{int a[50], n, i; 
clrscr( );
cout<<"n ENTER THE SIZE OF THE ARRAY: nt "; 
cin>>n; 
cout<<"n ENTER THE ELEMENTS:nt"; 
for( i = 0 ;i < n ;i + + ) 
cin>>a [ i ]; 
cout<<"n ELEMENTS BEFORE SORTING:nt"; 
for( i = 0 ; i < n ; i + + ) 
cout<<a[i]<<"t"; 
selsort obj; obj.sort(a,n); 
cout<<"n ELEMENTS AFTER SORTING ARE:nt"; 
for( i = 0 ; i < n ; i + + ) 
cout<<a[i]<<"t"; 
getch(); 
} 
OUTPUT:
LINEAR SEARCH 
10 20 30 40 50 60 70 
0 1 2 3 4 5 6 
•Here we want to search for ‘50’. 
• So compare ’50’ with a[i] where i=0,1,2,3,…. 
If (a[i]==50) 
Then element is found at location i that is 4 
Else 
i++ 
•Here the time complexity is O(n).
SOURCE CODE: 
#include < iostream.h > 
#include < conio.h > 
class lsearch 
{ 
private: 
int a[50], n, count, key; 
public: 
void init ( ); 
void linear ( ); 
}; 
void lsearch::init ( ) 
{ 
count = 0; 
} 
void lsearch::linear ( ) 
{ 
int i; 
clrscr ( ); 
cout<<"nENTER SIZE OF AN ARRAY :: "; 
cin>>n; 
cout<<"nnENTER "<<n<<" ELEMENTS INTO AN ARRAY ::"; 
for( i = 0; i < n; i + +) 
cin>> a [ i ]; 
cout<<"nnENTER SEARCH ELEMENT :: "; 
cin>>key; 
cout<<"nnELEMENTS IN ARRAY ARE :n";
for( i = 0; i < n; i + +) 
cout<< a [ i ]<<"t"; 
for( i = 0; i < n; i + + ) 
if(a [ i ] = = key) 
{ 
count + +; 
break; 
}i 
f( count = = 1 ) 
cout<<"nn ELEMENT IS FOUND IN 
"<< ( i + 1)<<" LOCATION"; 
else 
cout<<"nELEMENT IS NOT 
FOUND...."; 
} 
void main ( ) 
{ 
lsearch ob; 
clrscr ( ); 
ob.init (); 
ob.linear ( ); 
getch ( ); 
}
OUTPUT:
BINARY SEARCH 
•Here elements must be in Ascending/Descending order. 
•Consider the elements in ascending order 
711 15 23 46 64 71 83 
low high 
here low=0 and high=7 
Then calculate mid=(low+high)/2 
•Let us search for k=71 
•If (a[mid]==k) 
then element is found at ‘mid’ location 
•If(k<a[mid]) 
then high=mid-1 
else 
low=mid+1 
•Repeat the previous steps tell low and high are equal.
SOURCE CODE: 
/*Program To Implement Binary Search */ 
#include < iostream.h > 
#include < conio.h > 
class bsearch 
{ 
private : 
int a[50], n , x; 
public : 
void binary ( ); 
}; 
void bsearch::binary ( ) 
{ 
int i, j, temp, mid, beg, end; 
beg = 0; 
cout<<"nnENTER THE SIZE OF THE ARRAY :: "; 
cin>>n; 
end = n - 1; 
cout<<"nnENTER THE ELEMENTS OF THE ARRAY :: "; 
for( i = 0; i < n; i + +) 
cin>>a[i]; 
cout<<"nnELEMENTS BEFORE BEFORE SORTING ARE :: "; 
for( i = 0; i < n; i + + ) 
cout<< a [ i ]<<" ";
for( i = 0; i < n; i + + ) 
{ 
for( j = i + 1; j < n; j + +) 
{ 
if( a[ i ] > a[ j ] ) 
{ 
temp = a [ i ]; 
a[ i ] = a[ j ]; 
a[ j ] = temp; 
} 
} 
} 
cout<<"nnELEMENTS AFTER SORTING ARE :: "; 
for( i = 0; i < n; i + + ) 
cout<<a[ i ]<<" "; 
cout<<"nnENTER THE ELEMENT TO BE SEARCHED :: "; 
cin>>x; 
while ( beg < = end ) 
{ 
mid = ( beg + end ) / 2; 
if ( a [ mid ] = = x ) 
{
cout<<"nSEARCHING IS SUCCESSFUL AND THE ELEMENTS IS 
PRESENT AT "<< ( mid + 1 )<<" LOCATION"; 
return; 
} 
else if(x<a[mid]) 
end = mid - 1; 
else beg = mid + 1; 
} 
cout<<"n SEARCH IS UNSUCCESSFUL"; 
} 
void main ( ) 
{ 
bsearch obj; 
clrscr ( ); 
obj . binary ( ); 
getch ( ); 
} 
OUTPUT:
POLINOMIAL ADDITION AND MULTIPLICATION 
•1 expression: 3x2+2x+1 
Store all the coefficients 1,2,3 into an array1. 
•1 expression: 2x2+1x+2 
Store all the coefficients 2,1,2 into an array2. 
ADDITION: 
3x2+2x+1 
2x2+1x+2 
5x2+3x+3 
Store the result expression coefficients in array3
SOURCE CODE: 
/*Program To Demonstrate Addition And Multiplication Of Two Polynomial Expression */ 
#include < iostream.h > 
#include < conio.h > 
#define n 100 
class poly 
{ 
private: 
int a[n], b[n], add[n], mul[n], p, q, at; 
public: 
void init ( ); 
void input ( ); 
void process ( ); 
void display ( ); 
}; 
void poly :: init ( ) 
{ 
int i; 
for( i = 0; i < n; i + + ) 
a[ i ] = b [ i ] = add[ i ] = mul[ i ] = 0; 
}
void poly :: input ( ) 
{ 
int i; 
cout<<"nEnter Degree Of First Polynomial::"; 
cin>>p; 
cout<<"nEnter Degree Of Second 
Polynomial::"; 
cin>>q; 
cout<<"nEnter Values First 
Polynomialn"; 
for( i = 0; i <= p; i + + ) 
{ 
cout<<"nEnter X^"<<i<<" 
Th Coefficient"; 
cin>>a[ i ]; 
} 
cout<<"nEnter Values First 
Polynomialn"; 
for( i = 0; i <= q; i + + ) 
{ 
cout<<"nEnter X^"<<i<<" 
Th Coefficient"; 
cin>>b[ i ]; 
} 
}
void poly :: process ( ) 
{ 
int i, j; 
if( p > q ) 
at = p; 
else 
at = q; 
for ( i = 0; i <= at; i + +) 
add[ i ] = a[ i ] + b[ i ]; 
for( i = 0; i <= p; i + + ) 
for( j = 0; j <= q; j + + ) 
mul [ i + j ] + = a [ i ] * b [ j ]; 
} 
void poly :: display ( ) 
{ 
int i; 
cout<<"Addition Of Two Polynomial Expressions Arenn"; 
for( i = at; i >=0 ; i - -) 
cout<<add[i]<<"X^"<<i<<"+"; 
cout<<"nnMultiplecation Of Two Polynomial Expressions Arenn"; 
for( i = p + q; i > = 0; i - -) 
cout<<mul[i]<<"X^"<< i <<"+"; 
}
void main() 
{ 
poly ob; 
clrscr ( ); 
ob.init ( ); 
ob.input ( ); 
ob.process ( ); 
ob.display ( ); 
getch ( ); 
} 
OUTPUT:
SINGLE LINKED LIST 
THEORY: 
Figure shows a Linked List. Each item in the list is called a node and contain two fields, a data 
field and a next address field. The data field holds the actual element on the list. The next address 
field contains the address of the next node in the list. Such an address which is used to access a 
particular node, is known as a pointer. The entire linked list is accesses from an external pointer list, 
that points to the first node in the list. The next field of last node in the list contains a special value, 
known as NULL. The null pointer is used to signal the end of the list. 
The singly-linked list is the most basic of all the linked data structures. A singly-linked list 
is simply a sequence of dynamically allocated objects, each of which refers to its successor in the 
list. Despite this obvious simplicity, there are myriad implementation variations. 
The following code inserts a node after an existing node in a singly linked list. The diagram 
shows how it works. Inserting a node before an existing one cannot be done; instead, you have to 
locate it while keeping track of the previous node.
Similarly, we have functions for removing the node after a given node, and for removing a 
node from the beginning of the list. The diagram demonstrates the former. To find and 
remove a particular node, one must again keep track of the previous element.
SOURCE CODE: 
/*Program To Implement Single Linked list */ 
#include< stdio.h > 
#include < iostream.h > 
#include < conio.h > 
#include < process.h > 
#include< alloc.h > 
class slist 
{ 
private: 
struct list 
{i 
nt data; 
struct list *next; 
}*start,*temp,*curr,*add,*tem,*addr; 
public: 
void init ( ); 
void create ( ); 
void disp ( ); 
list *search ( int ); 
void insert ( ); 
void del ( ); 
};
void slist :: init ( ) 
{ 
start = temp = curr = NULL; 
} 
void slist::create ( ) 
{ 
char ch; 
temp = new list; 
cout<<"n ENTER THE DATA TO BE STORED n"; 
cin>> temp->data; 
temp->next = NULL; 
start = curr = temp; 
cout<<"n DO YOU WANT TO INSERT ANOTHER NODE (Y/N)"; 
cin>>ch; 
while( ch = = 'y' ) 
{ 
temp = new list; 
cout<<"n ENTER DATA TO BE STORED:n"; 
cin>>temp->data; 
temp->next = NULL; 
curr->next = temp; 
curr = temp; 
cout<<"n DO YOU WANT TO INSERT ANOTHER NODE (Y/N):"; 
cin>>ch; 
} 
}
void slist :: disp ( ) 
{ 
if( start = = NULL) 
cout<<"n LIST IS EMPTY"; 
else 
{ 
cout<<"n DATA PRESENT IN A LIST IS n"; 
temp = start; 
while( temp -> next ! = NULL) 
{ 
cout<<"|"<<temp->data<<"|"<<temp->next<<"|-->"; 
temp = temp -> next; 
} 
cout<<"|"<<temp->data<<"|"<<temp->next<<"|"; 
} 
} 
slist::list *slist :: search( int key) 
{ 
temp = start; 
while( temp -> next ! = NULL) 
{ 
if( temp->data = = key ) 
return temp; 
else 
temp = temp->next; 
}i 
f( temp->next = = NULL )
if( temp->data = = key ) 
return temp; 
else 
return NULL; 
} 
void slist:: insert ( ) 
{ 
int key; 
cout<<"n ENTER DATA AFTER WHICH WE CAN INSERT NEW NODE:"; 
cin>>key; 
add=search(key); 
if( add = = NULL ) 
cout<<"n NODE IS NOT FOUND"; 
else 
{ 
temp = new list; 
cout<<"n ENTER INSERTED ELEMENT"; 
cin>>temp->data; 
if( add->next = = NULL) 
{ 
temp->next = NULL; 
add->next = temp; 
curr = temp; 
}
else 
{ 
addr = add->next; 
add->next = temp; 
temp->next = addr; 
} 
} 
} 
void slist :: del ( ) 
{ 
int key; 
cout<<"n ENTER NODE DATA SHOULD BE DELETE:n"; 
cin>>key; 
add = search ( key ); 
if( add = = NULL ) 
cout<<"n NODE IS NOT FOUNDn"; 
else 
if( curr = = add ) 
{ 
curr = start; 
while( curr->next ! = NULL) 
{ 
temp = curr; 
curr = curr->next; 
}
free ( curr ); 
curr = temp; 
curr->next = NULL; 
} 
else 
if( start = = add ) 
{ 
temp = start; 
start = start->next; 
free( temp ); 
} 
else 
{ tem = add->next; 
temp = start; 
while( temp-> next ! = add) 
temp = temp->next; 
temp->next = tem; 
free( add ); 
} 
} 
void main ( ) 
{ 
slist ob; 
int key, ch; 
list *temp; 
clrscr ( ); 
cout<<"n * * * SINGLE LINKED LIST OPERATION * * * n";
cout<<"n 1. CREATE n 2. DISPLAY n 3. INSERT n 4. DELETE n 5. SEARCH n 6.EXIT n"; 
cout<<"n *************************n"; 
do 
{ 
cout<<"n ENTER YOUR CHOICE n"; 
cin>>ch; 
switch ( ch ) 
{ 
case 1: ob.create ( ); 
break; 
case 2: ob.disp ( ); 
break; 
case 3: ob.insert ( ); 
break; 
case 4: ob.del ( ); 
break; 
case 5: cout<<"n ENTER THE ELEMENT TO SEARCH"; 
cin>>key; 
temp=ob.search(key); 
if( temp = = NULL) 
cout<<"n ELEMENT IS NOT FOUND n"; 
else 
cout<<"n ELEMENT IS FOUND n"; 
break; 
case 6: exit(0); 
default: cout<<"n INVALID CHOICE n"; 
} 
}while( ch ! = 0 ); 
getch ( ); 
}
OUTPUT:
SINGLE CIRCULAR LINKED LIST 
THEORY: 
The linked list that we have seen so far is often know as linear lists. The elements of such 
a linked list can be accessed, first by setting up a pointer pointing to the first node in the list and 
then traversing the entire list using this pointer. Although a linear linked list is a useful data 
structure, it has several shortcomings.
SOURCE CODE: 
/* Program to implement single circular linked list */ 
#include<iostream.h> 
#include<conio.h> 
#include<process.h> 
#include<alloc.h> 
class clist 
{ 
private: 
struct list 
{ 
int data; 
struct list *next; 
}*start,*temp,*curr,*add,*tem,*addr; 
public: 
void init(); void creat(); 
void display(); list *search(int); 
void insert(); void del(); 
}; 
void clist::init() 
{ 
start=temp=curr=NULL; 
}
void clist::creat() 
{ 
char ch; 
temp=new list; 
cout<<"n ENTER ENTER DATA TO BE STORED ::"; 
cin>>temp->data; 
cout<<"nADDRESS OF STARTING NODE :: "<<temp; 
temp->next=start; 
start=curr=temp; 
cout<<"nDO YOU WANT TO INSERT ANOTHER NODE (y/n) :: "; 
cin>>ch; 
while(ch=='y') 
{ 
temp=new list; 
cout<<"n ENTER DATA TO BE STORED :: "; 
cin>>temp->data; 
temp->next=start; 
curr->next=temp; 
curr=temp; 
cout<<"nDO YOU WANT TO INSERT ANOTHER NODE (y/n) :: "; 
cin>>ch; 
} 
}
void clist::display() 
{ 
if(start==NULL) 
cout<<"nLIST IS EMPTY....."; 
else 
cout<<"nDATA PRESENT IN A LIST IS :: n"; 
temp=start; 
while(temp->next!=start) 
{ 
cout<<"|"<<temp->data<<"|"<<temp->next<<"|-->"; 
temp=temp->next; 
} 
cout<<"|"<<temp->data<<"|"<<temp->next<<"|"; 
} 
clist::list *clist::search(int key) 
{ 
temp=start; 
while(temp->next!=start) 
{ 
if(temp->data==key) 
return temp; 
else 
temp=temp->next; 
}
if(temp->next==NULL) 
{ 
if(temp->data==key) 
return temp; 
else 
return NULL; 
} return NULL; 
} 
void clist::insert() 
{ 
int key; 
cout<<"n ENTER DATA AFTER WHICH WE CAN INSERTED NEW NODE :: 
"; 
cin>>key; 
add=search(key); 
if(add==NULL) 
cout<<"n NODE IS NOT FOUND ...."; 
else 
{ 
temp=new list; 
cout<<"n ENTER INSERTED ELEMENT :: "; 
cin>>temp->data;
if(add->next==start) 
{ 
temp->next=start; 
add->next=temp; 
curr=temp; 
} 
else 
{ 
addr=add->next; 
add->next=temp; 
temp->next=addr; 
} 
} 
} 
void clist::del() 
{ 
int key; 
cout<<"nEnter node to deleted:"; 
cin>>key; 
add=search(key); 
if(add==NULL) 
cout<<"nNode is not found"; 
else if(curr==add)
{ 
curr=start; 
while(curr->next!=start) 
{ 
temp=curr; 
curr=curr->next; 
} free(curr); 
curr=temp; 
curr->next=start; 
} 
else if(start==add) 
{ 
temp=start; 
start=start->next; 
free(temp); 
} 
else 
{ 
tem=add->next; 
temp=start; 
while(temp->next!=add) 
temp=temp->next; 
temp->next=tem; 
free(add); 
} 
}
void main() 
{ 
clist ob; 
int key,ch; 
clist::list *temp; 
clrscr(); 
cout<<"nCIRCULAR LINKED LIST n"; 
cout<<"n1.Createn2.Displayn3.Insertn4.Deleten5.Searchn6.Exitn"; 
do 
{ 
cout<<"nEnter your choice"; 
cin>>ch; 
switch(ch) 
{ 
case 1:ob.creat(); 
break; 
case 2:ob.display(); 
break; 
case 3:ob.insert(); 
break; 
case 4:ob.del(); 
break;
case 5:cout<<"nEnter search element"; 
cin>>key; 
temp=ob.search(key); 
if(temp==NULL) 
cout<<"nElement is not found"; 
else 
cout<<"nElement is found"; 
break; 
case 6:exit(0); 
default:cout<<"Invalid choice"; 
} 
}while(ch!=6); 
getch(); 
}
OUTPUT:
DOUBLE LINKED LIST 
AIM: Write a program in C++ to implement DOUBLE LINKED LIST 
THEORY: 
A two-way list is a linear collection of data elements, called nodes, where each node N is 
divided into three parts: 
•An item data field. 
•A pointer field next which contains the location of the next node in the list. 
•A pointer field prev which contains the location of the previous node in the list. 
The list requires two list pointer variables: FIRST, which points to the first node in the list, and 
LAST, which points to the last node in the list. The figure contains a schematic diagram of such a 
list. Observe that the null pointer appears in the next field of the last node in the list and also in the 
prev field of the first node in the list. Observe that, using the variable FIRST and the pointer field 
next, we can traverse a two-way list in the forward direction as before. On the other hand, using the 
variable LAST and the pointer field prev, we can also traverse the list in the backward direction.
OPERATION ON TWO-WAY LISTS: 
1. Traversing. 
2. Searching. 
3. Deleting 
4Inserting
SOURCE CODE: 
/* Program to implement Double linked list */ 
#include<iostream.h> 
#include<conio.h> 
#include<process.h> 
#include<alloc.h> 
class dlist 
{ 
private: 
struct list 
{ 
int data; 
struct list *next,*prev; 
}*start,*temp,*curr,*add,*addr,*tem; 
public: 
void init(); 
void creat(); void display(); 
list *search(int); 
void insert(); void del(); 
}; 
void dlist::init() 
{ 
start=temp=curr=NULL; 
}
void dlist::creat() 
{ 
char ch; 
temp=new list; 
cout<<"nENTER DATA TO BE STORED :: "; 
cin>>temp->data; 
cout<<"n STARTING NODE ADDRESS :: "<<temp<<"n"; 
temp->next=NULL; 
temp->prev=NULL; 
start=curr=temp; 
cout<<"n DO YOU WANT TO INSERT ANOTHER NODE 
(y/n) :: "; 
cin>>ch; 
while(ch=='y') 
{ 
temp=new list; 
cout<<"nENTER DATA TO BE STORED :: "; 
cin>>temp->data; 
temp->next=NULL; 
temp->prev=curr; curr->next=temp; 
curr=temp; 
cout<<"nDO YOU WANT TO INSERT ANOTHER 
NODE (y/n) :: "; 
cin>>ch; 
} 
}
void dlist::display() 
{ 
if(start==NULL) 
cout<<"n LIST IS EMPTY...."; 
else 
{ 
cout<<"n DATA PRESENT IN A LISTn:::"; 
temp=start; 
while(temp->next!=NULL) 
{ 
cout<<"|"<<temp->prev<<"|"<<temp->data<<"|"<<temp->next<<"|-- 
>"; 
temp=temp->next; 
} 
cout<<"|"<<temp->prev<<"|"<<temp->data<<"|"<<temp->next<<"|"; 
} 
} 
dlist::list *dlist::search(int key) 
{ 
temp=start; 
while(temp->next!=NULL) 
{ 
if(temp->data==key)
return temp; 
else 
temp=temp->next; 
}i 
f(temp->next==NULL) 
{ 
if(temp->data==key) 
return temp; 
else 
return NULL; 
} return NULL; 
} 
void dlist::insert() 
{ 
int key; 
cout<<"nENTER DATA AFTER WHICH WE CAN INSERT A 
NEW NODE :: "; 
cin>>key; 
add=search(key); 
if(add==NULL) 
cout<<"n NODE IS NOT FOUND....."; 
else 
tem=new list;
cout<<"n ENTER ELEMENT TO BE SEARCHED :: "; 
cin>>tem->data; 
if(add->next==NULL) 
{ 
tem->next=NULL; 
tem->prev=add; 
add->next=tem; 
curr=tem; 
} 
else 
{ 
addr=add->next; 
add->next=tem; 
tem->next=addr; 
tem->prev=add; 
} 
} 
void dlist::del() 
{ 
int key; 
cout<<"n ENTER NODE DATA TO BE DELETED :: "; 
cin>>key; 
add=search(key); 
if(add==NULL) 
cout<<"n NODE IS NOT FOUND :: "; 
else
if(curr==add) 
{ 
curr=start; 
while(curr->next!=NULL) 
{ 
temp=curr; 
curr=curr->next; 
} 
free(curr); 
curr=temp; 
curr->next=NULL; 
} 
else if(start==NULL) 
{ 
temp=start; 
start=start->next; 
free(temp); 
} 
else 
{ 
tem=add->next; 
temp=start; 
while(temp->next!=add) 
temp=temp->next; 
temp->next=tem; 
free(add); 
} 
}
void main() 
{ 
dlist ob; 
int key,ch; 
dlist::list *temp; 
clrscr(); 
cout<<"**********DOUBLE LINKED LIST**********"; 
cout<<"n1.Createn2.Displayn3.Insertn4.Deleten5.Searchn6.Exitn"; 
do 
{ 
cout<<"nENTER YOUR CHOICE :: "; 
cin>>ch; 
switch(ch) 
{ 
case 1:ob.creat(); 
break; 
case 2:ob.display(); 
break; 
case 3:ob.insert(); 
break; 
case 4:ob.del(); 
break;
case 5:cout<<"n ENTER SEARCH ELEMENT :: "; 
cin>>key; 
temp=ob.search(key); 
if(temp==NULL) 
cout<<"n ELEMENT IS NOT FOUND...."; 
else 
cout<<"n ELEMENT IS FOUND....."; 
break; 
case 6:exit(0); 
default:cout<<"n INVALID CHOICE...."; 
} 
}while(ch!=6); 
getch(); 
}
OUTPUT:
GRAPH TRAVERSING: DEPTH FIRST SEARCH 
THEORY: 
•DFS is an uninformed search that progresses by expanding the first child node 
of the search tree that appears and thus going deeper and deeper until a goal node 
is found, or until it hits a node that has no children. Then the search backtracks, 
returning to the most recent node it hadn't finished exploring. In a non-recursive 
implementation, all freshly expanded nodes are added to a LIFO stack for 
exploration. 
•Space complexity of DFS is much lower than BFS (breadth-first search). It also 
lends itself much better to heuristic methods of choosing a likely-looking branch. 
Time complexity of both algorithms are proportional to the number of vertices plus 
the number of edges in the graphs they traverse (O(|V| + |E|)).
SOURCE CODE: 
/*Program To Implement Depth First Search */ 
#include < iostream.h > 
#include < conio.h > 
#define MAX 20 
class depth 
{ 
private: int a[MAX][MAX], visited[MAX]; 
int n, top; 
public: void init ( ); 
void input ( ); 
void dfs ( int ); 
}; 
void depth::init ( ) 
{ int i, j; 
for( i = 0; i < MAX; i + + ) 
{ visited[ i ] = 0; 
for( j =0; j < MAX ; j + + ) 
a[ i ] [ j ] = 0; 
} top = - 1; 
} 
void depth::input ( ) 
{ int i, j; 
cout<<"nENTER NUMBER OF NODES IN A GRAPH :: ";
cin>>n; 
cout<<"nENTER ADJACENCY MATRIX FOR A GRAPH :: n"; 
for( i = 1; i <= n; i + +) 
for( j = 1; j <= n; j + + ) 
cin>>a[ i ][ j ]; 
} 
void depth::dfs ( int v) 
{ int i; 
visited[v] = 1; 
cout<<v<<"->"; 
for( i = 1; i <= n; iI + + ) 
if( a [ v ] [ i ] = = 1 && visited [ i ] = = 0) 
dfs ( i ); 
} 
void main ( ) 
{ depth ob; 
int start; 
clrscr ( ); 
ob.init ( ); 
ob.input ( ); 
cout<<"nSTARTING NODE FOR DFS TRAVERSING :: "; 
cin>>start; 
cout<<"nDEPTH FIRST SEARCH TRAVERSING IS ::nn"; 
ob.dfs ( start ); 
getch ( ); 
}
OUTPUT:
GRAPH TRAVERSING: BREADTH FIRST 
THEORY: 
•BFS is an uninformed search method that aims to expand and examine all nodes of 
a graph or combinations of sequence by systematically searching through every solution. In other 
words, it exhaustively searches the entire graph or sequence without considering the goal until it 
finds it. 
•From the standpoint of the algorithm, all child nodes obtained by expanding a node are added 
to a FIFO queue. In typical implementations, nodes that have not yet been examined for their 
neighbors are placed in some container (such as a queue or linked list) called "open" and then once 
examined are placed in the container "closed". 
Algorithm for Breadth First Search 
1.Enqueue the root node. 
2.Dequeue a node and examine it. 
•If the element sought is found in this node, quit the search and return a result. 
•Otherwise enqueue any successors (the direct child nodes) that have not yet been 
discovered. 
3.If the queue is empty, every node on the graph has been examined – quit the search and 
return "not found". 
4.Repeat from Step 2.
SOURCE CODE: 
/*Program To Implement Breadth First Search */ 
#include < iostream.h > 
#include < conio.h > 
#define MAX 20 
class breadth 
{ 
private: 
int a[MAX][MAX], visited[MAX], queue[50]; 
int n, front, rear; 
public: 
void init ( ); 
void input ( ); 
void bfs ( ); 
}; 
void breadth::init ( ) 
{ 
int i, j; 
for( i = 0; i < MAX; i + + ) 
{ 
visited [ i ] = 0; 
for( j = 0; j < MAX; j + + ) 
a[ i ] [ j ] = 0; 
} front = rear = - 1; 
}
void breadth::input ( ) 
{ 
int i, j; 
cout<<"nENTER NUMBER OF NODES IN A GRAPH :: "; 
cin>>n; 
cout<<"nENTER ADJACENCY MATRIX FOR A GRAPH :: n"; 
for( i = 1;i <= n; i + + ) 
for( j = 1; j <= n; j + + ) 
cin>>a[ i ][ j ]; 
} 
void breadth::bfs ( ) 
{ 
int i, start; 
cout<<"nSTARTING NODE FOR BFS TRAVERSING :: "; 
cin>>start; 
cout<<"n BREADTH FIRST SEARCH TRAVERSING IS:: n t"; 
cout<<start; 
visited[ start ] = 1; 
rear + +; 
front + +; 
queue[ rear ] = start; 
while(front <= rear) 
{ 
start = queue[front]; 
front + +;
for( i =1; i <= n; i + + ) 
{ 
if(a[ start ][ i ] = =1 && visited[ i ] = = 0) 
{ 
cout<<"->"<<i; 
visited[ i ] =1; 
rear + +; 
queue [ rear ] = i; 
} 
} 
} 
} 
void main ( ) 
{ 
breadth ob; 
int start; 
clrscr ( ); 
ob.init ( ); 
ob.input ( ); 
ob.bfs ( ); 
getch ( ); 
}
OUTPUT:
SHORTEST PATH FOR GRAPH 
THEORY: 
Shortest path is nothing but the path which lies between two nodes with the lowest cost. In a 
graph contain so many paths are existed between two nodes (source node to destination node) to 
choose the lowest cost path to reach from source node to destination node is nothing but shortest 
path algorithm. Shortest path algorithm was first proposed by E. W. DIJKSTRA. 
SOURCE CODE: 
/*Program To Implement Shortest Path for Graph */ 
#include < iostream.h > 
#include < conio.h > 
#define INF 9999 
class stpath 
{ 
private: 
int i, j, k; 
public: 
void spath(int [ ][20], int ); 
void display(int [ ][20], int ); 
};
void stpath::spath(int a[ ][20], int n) 
{ 
for( i = 0 ;i < n; I + + ) 
for( j = 0; j < n; j + + ) 
if(a[ i ] [ j ] = = 0) 
a[ i ][ j ] = INF; 
cout<<"nADJACENCY MATRIX OF COST OF EDGES ARE ::"; 
display( a, n ); 
for( k = 0; k < n; k + + ) 
for( i = 0; i < n; i + + ) 
for( j = 0; j < n; j + + ) 
if( a[ i ][ j ] > a[ i ] [ k] + a[ k ][ i ]) 
a[ i ][ j ] = a[ i ][ k ] + a[ k ][ j ]; 
cout<<"nADJACENCY MATRIX OF LOWEST COST OF EDGES ARE ::n"; 
display(a, n); 
} 
void stpath::display(int a[ ] [20], int n) 
{ 
for( i = 0; i < n; i + + ) 
{ 
for( j = 0; j < n; j + + ) 
cout<<a[ i ][ j ]<<"t"; 
cout<<"n"; 
} 
}
void main() 
{ 
int i, j , n , a[20][20]; 
stpath ob; 
clrscr(); 
cout<<"nENTER NUMBER OF NODES IN A GRAPH :: "; 
cin>>n; 
cout<<"nENTER ADJACENCY MATRIX ::n"; 
for( i = 0; i < n; i + + ) 
for( j = 0; j < n; j + + ) 
{ 
cout<<"Enter "<<i+1<<" To "<<j+1<<" Node Distance"; 
cin>>a[ i ] [ j ]; 
} 
ob.spath(a, n); 
getch ( ); 
}
OUTPUT:

More Related Content

What's hot

Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
OdessaJS Conf
 
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
OdessaJS Conf
 
Java Practical File Diploma
Java Practical File DiplomaJava Practical File Diploma
Java Practical File Diploma
mustkeem khan
 
Container adapters
Container adaptersContainer adapters
Container adapters
mohamed sikander
 
Python opcodes
Python opcodesPython opcodes
Python opcodes
alexgolec
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2goMoriyoshi Koizumi
 
Linked list imp of list
Linked list imp of listLinked list imp of list
Linked list imp of list
Elavarasi K
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
Bob Tiernay
 
Меняем javascript с помощью javascript
Меняем javascript с помощью javascriptМеняем javascript с помощью javascript
Меняем javascript с помощью javascript
Pavel Volokitin
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
pratikbakane
 
Myraytracer
MyraytracerMyraytracer
Myraytracer
kedar nath
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Sergey Platonov
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
pratikbakane
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
pratikbakane
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
Knoldus Inc.
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
Designveloper
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
Kyung Yeol Kim
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
pratikbakane
 
TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.
lnikolaeva
 
20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugsComputer Science Club
 

What's hot (20)

Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
 
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
 
Java Practical File Diploma
Java Practical File DiplomaJava Practical File Diploma
Java Practical File Diploma
 
Container adapters
Container adaptersContainer adapters
Container adapters
 
Python opcodes
Python opcodesPython opcodes
Python opcodes
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
Linked list imp of list
Linked list imp of listLinked list imp of list
Linked list imp of list
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
 
Меняем javascript с помощью javascript
Меняем javascript с помощью javascriptМеняем javascript с помощью javascript
Меняем javascript с помощью javascript
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
Myraytracer
MyraytracerMyraytracer
Myraytracer
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.
 
20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs
 

Viewers also liked

Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
Äshïsh Jäïn
 
BTree, Data Structures
BTree, Data StructuresBTree, Data Structures
BTree, Data StructuresJibrael Jos
 
Binary tree
Binary  treeBinary  tree
Binary tree
Vanitha Chandru
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary tree
Zaid Shabbir
 
Trees data structure
Trees data structureTrees data structure
Trees data structure
Sumit Gupta
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)
Trupti Agrawal
 

Viewers also liked (6)

Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
 
BTree, Data Structures
BTree, Data StructuresBTree, Data Structures
BTree, Data Structures
 
Binary tree
Binary  treeBinary  tree
Binary tree
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary tree
 
Trees data structure
Trees data structureTrees data structure
Trees data structure
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)
 

Similar to DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY

This is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdfThis is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdf
kostikjaylonshaewe47
 
Lab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxLab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docx
teyaj1
 
C++ TUTORIAL 3
C++ TUTORIAL 3C++ TUTORIAL 3
C++ TUTORIAL 3
Farhan Ab Rahman
 
How do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdfHow do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdf
feelinggift
 
DATA STRUCTURE USING C & C++
DATA STRUCTURE USING C & C++DATA STRUCTURE USING C & C++
DATA STRUCTURE USING C & C++
mustkeem khan
 
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdfDoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
aathiauto
 
Write a C program that reads the words the user types at the command.pdf
Write a C program that reads the words the user types at the command.pdfWrite a C program that reads the words the user types at the command.pdf
Write a C program that reads the words the user types at the command.pdf
SANDEEPARIHANT
 
Computer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfComputer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdf
HIMANSUKUMAR12
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
kinan keshkeh
 
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docxfilesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
ssuser454af01
 
Please teach me how to fix the errors and where should be modified. .pdf
Please teach me how to fix the errors and where should be modified. .pdfPlease teach me how to fix the errors and where should be modified. .pdf
Please teach me how to fix the errors and where should be modified. .pdf
amarndsons
 
CBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical fileCBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical file
Pranav Ghildiyal
 
linkedlist.pptx
linkedlist.pptxlinkedlist.pptx
linkedlist.pptx
MeghaKulkarni27
 
54602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee0108310154602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee01083101
premrings
 
I want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdfI want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdf
bermanbeancolungak45
 
coding in C- Create a function called reverseList that takes the head.docx
coding in C- Create a function called reverseList that takes the head.docxcoding in C- Create a function called reverseList that takes the head.docx
coding in C- Create a function called reverseList that takes the head.docx
tienlivick
 

Similar to DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY (20)

This is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdfThis is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdf
 
Lab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxLab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docx
 
C++ TUTORIAL 3
C++ TUTORIAL 3C++ TUTORIAL 3
C++ TUTORIAL 3
 
How do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdfHow do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdf
 
C++ file
C++ fileC++ file
C++ file
 
C++ file
C++ fileC++ file
C++ file
 
DATA STRUCTURE USING C & C++
DATA STRUCTURE USING C & C++DATA STRUCTURE USING C & C++
DATA STRUCTURE USING C & C++
 
C program
C programC program
C program
 
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdfDoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
 
Write a C program that reads the words the user types at the command.pdf
Write a C program that reads the words the user types at the command.pdfWrite a C program that reads the words the user types at the command.pdf
Write a C program that reads the words the user types at the command.pdf
 
Computer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfComputer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdf
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docxfilesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
 
Please teach me how to fix the errors and where should be modified. .pdf
Please teach me how to fix the errors and where should be modified. .pdfPlease teach me how to fix the errors and where should be modified. .pdf
Please teach me how to fix the errors and where should be modified. .pdf
 
CBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical fileCBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical file
 
linkedlist.pptx
linkedlist.pptxlinkedlist.pptx
linkedlist.pptx
 
Final ds record
Final ds recordFinal ds record
Final ds record
 
54602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee0108310154602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee01083101
 
I want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdfI want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdf
 
coding in C- Create a function called reverseList that takes the head.docx
coding in C- Create a function called reverseList that takes the head.docxcoding in C- Create a function called reverseList that takes the head.docx
coding in C- Create a function called reverseList that takes the head.docx
 

More from Malikireddy Bramhananda Reddy

DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDY
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDYDATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDY
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDYMalikireddy Bramhananda Reddy
 
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyDatastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyMalikireddy Bramhananda Reddy
 
C notes by m v b reddy(gitam)imp notes all units notes 5 unit order
C notes by m v b  reddy(gitam)imp  notes  all units notes  5 unit orderC notes by m v b  reddy(gitam)imp  notes  all units notes  5 unit order
C notes by m v b reddy(gitam)imp notes all units notes 5 unit orderMalikireddy Bramhananda Reddy
 

More from Malikireddy Bramhananda Reddy (20)

M v bramhananda reddy dsa complete notes
M v bramhananda reddy dsa complete notesM v bramhananda reddy dsa complete notes
M v bramhananda reddy dsa complete notes
 
AVL TREE PREPARED BY M V BRAHMANANDA REDDY
AVL TREE PREPARED BY M V BRAHMANANDA REDDYAVL TREE PREPARED BY M V BRAHMANANDA REDDY
AVL TREE PREPARED BY M V BRAHMANANDA REDDY
 
B-TREE PREPARED BY M V BRAHMANANDA REDDY
B-TREE PREPARED BY M V BRAHMANANDA REDDYB-TREE PREPARED BY M V BRAHMANANDA REDDY
B-TREE PREPARED BY M V BRAHMANANDA REDDY
 
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDY
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDYDATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDY
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDY
 
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyDatastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
 
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDYC LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
 
DATASTRUCTURES UNIT-1
DATASTRUCTURES UNIT-1DATASTRUCTURES UNIT-1
DATASTRUCTURES UNIT-1
 
Data representation UNIT-1
Data representation UNIT-1Data representation UNIT-1
Data representation UNIT-1
 
C SLIDES PREPARED BY M V B REDDY
C SLIDES PREPARED BY  M V B REDDYC SLIDES PREPARED BY  M V B REDDY
C SLIDES PREPARED BY M V B REDDY
 
C AND DATASTRUCTURES PREPARED BY M V B REDDY
C AND DATASTRUCTURES PREPARED BY M V B REDDYC AND DATASTRUCTURES PREPARED BY M V B REDDY
C AND DATASTRUCTURES PREPARED BY M V B REDDY
 
C PROGRAMS
C PROGRAMSC PROGRAMS
C PROGRAMS
 
C LANGUAGE NOTES
C LANGUAGE NOTESC LANGUAGE NOTES
C LANGUAGE NOTES
 
C notes by m v b reddy(gitam)imp notes all units notes 5 unit order
C notes by m v b  reddy(gitam)imp  notes  all units notes  5 unit orderC notes by m v b  reddy(gitam)imp  notes  all units notes  5 unit order
C notes by m v b reddy(gitam)imp notes all units notes 5 unit order
 
Vcs29
Vcs29Vcs29
Vcs29
 
Vcs28
Vcs28Vcs28
Vcs28
 
Vcs26
Vcs26Vcs26
Vcs26
 
Vcs24
Vcs24Vcs24
Vcs24
 
Vcs23
Vcs23Vcs23
Vcs23
 
Vcs22
Vcs22Vcs22
Vcs22
 
Vcs21
Vcs21Vcs21
Vcs21
 

Recently uploaded

Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 

Recently uploaded (20)

Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 

DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY

  • 1. DATA STRUCTURES ( C++ ) DATASTRUCTURES PROGRAMMING CONCEPTS Developed by, M.V.B.REDDY,CSE Associate professor, Dept. of CSE, GST, GITAM UNIVERSITY. Email ID : bramhareddy999@gmail.com
  • 2.  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. STACK USING ARRAYS  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
  • 3. 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; }
  • 4. sp + + ; a [ sp ] = data; } void stack :: pop ( ) {i f ( 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); };
  • 5. 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 ( ); }
  • 7.  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 STACK node address USING field. LINKED LIST  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.
  • 8. Source code: #include<conio.h> #include<iostream.h> 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;
  • 9. start->next=NULL; top=start; } else { temp=new node; temp->data=d; temp->next=top; top=temp; } } void disp() { while(top!=NULL) { cout<<top->data<<"t"; top=top->next; } } }; void main() { st ob; int ch; clrscr();
  • 10. while(ch) { cout<<"Enter ur choice"; cout<<"0 STOPn1 CREATEn 2 READ"; cin>>ch; if(ch==1) ob.create(); else if(ch==2) ob.disp(); } } OUTPUT:
  • 11.  Here we will take an array a[5],and two variables front, rear points to -1.  WRITE: QUEUE USING ARRAYS  Here will insert the element into the queue using rear variable.  Here check for the Overflow condition.  READ:  Here we will retrieve the elements from the queue using front variable.  Here check for the Underflow condition.  This follows the FIFO concept. rear -1 0 1 2 3 4 front
  • 12. SOURCE CODE: /* Program To Implement Queue using Array */ #include< iostream.h > #include< conio.h > #include< process.h > #define MAX 10 class queue { private : int front, rear, a [ MAX ]; public : void init ( ); void write ( int ); void read ( ); void count ( ); void display ( ); }; void queue :: init ( ) {f ront = rear = - 1; } void queue :: write ( int data) { if ( rear = = ( MAX - 1 ) ) cout<<"n QUEUE IS OVERFLOW......"; else a [ + + rear ] = data; } void queue :: read ( ) { if( front = = rear ) cout<<"n QUEUE IS UNDERFLOW....."; else cout<<"n DELETED ELEMENT IN QUEUE IS :: "<<a[++front]; }
  • 13. void queue :: count ( ) { cout<<"n NUMBER OF ELEMENTS IN A QUEUE ARE :: "<<(rear-front); } void queue :: display ( ) { cout<<"n ELEMENTS IN A QUEUE ARE:: "; for( int i = (front + 1); i < = rear; i + + ) cout<< a [ i ]<<"t"; } void main ( ) { queue ob; int ch,data; clrscr ( ); ob.init ( ); cout<<"n*****QUEUE OPERATIONS****n"; cout<<"n1.Write "; cout<<"n2.Read "; cout<<"n3.Count"; cout<<"n4.Display"; cout<<"n5.Exit"; cout<<"**************************n";
  • 14. do { cout<<"n ENTER YOUR CHOICE :: "; cin>>ch; switch ( ch ) { case 1:cout<<"n ENTER ELEMENT TO BE INSERTED IN QUEUE :: "; cin>>data; ob.write ( data ); break; case 2:ob.read ( ); break; case 3:ob.count ( ); break; case 4:ob.display ( ); break; case 5:exit ( 0 ); break; default :cout<<"n INVALID CHOICE..."; }} while( ch ! = 5 ); getch ( ); }
  • 16.  Here we will create linked list with ‘n’ nodes one after another 10,20,30 etc.  If we try to print the elements it will display as 10,20,30. which follows FIFO Queue concept. using linked list
  • 17. SOURCE CODE: /* Program To Implement Queue using Linked List */ #include < iostream.h > #include< conio.h > #include < alloc.h > #define NULL 0 class node {i nt data; node *next; public: void create ( node *); void print ( node *); }; void node :: create (node *list) { cout<<"n ENTER THE INPUT NO :: "; cout<<"n TYPE 999 AT THE END :: "; cin>>list->data; if(list -> data = = 999) list->next = NULL; else {l ist -> next = new node; create( list -> next); } return; }
  • 18. void node :: print (node *list) {i f( list -> next ! = 0) { cout<< list->data; cout<<"->"; } else return; print( list -> next); } void main ( ) { node *head, ob; clrscr ( ); head = new node; ob.create ( head ); cout<<"n QUEUE ELEMENTS ARE:: "; ob.print( head ); cout<<"999"; getch ( ); }
  • 20.  A binary tree is a tree data structure in which each node has at most two children. Typically the child nodes are called left and right. Binary trees are commonly used to implement binary search trees and binary heaps.  Starting at the root of a binary tree, there are three main steps that can be performed and the order in which they are performed define the traversal type. BINARY TREE USING RECURSION  There are 3 types of traversals:  1. Pre-Order  2. In-Order  3. Post-Order  To traverse a non-empty binary tree in preorder, perform the following operations recursively at each node, starting with the root node: 1. Visit the root. 2. Traverse the left sub tree. 3. Traverse the right sub tree.  To traverse a non-empty binary tree in in order, perform the following operations recursively at each node, starting with the root node: 1. Traverse the left sub tree. 2. Visit the root. 3. Traverse the right sub tree.  To traverse a non-empty binary tree in post order, perform the following operations recursively at each node, starting with the root node: 1. Traverse the left sub tree. 2. Traverse the right sub tree. 3. Visit the root.
  • 21. 15 7 22 BINARY TREE: Preorder:- 15,7,22 will be displayed . Post order:- 7,22,15 will be displayed . In order:- 7,15,22 will be displayed .
  • 22. SOURCE CODE: /* Program To Implement Binary Tree Traversing */ #include < iostream.h > #include < conio.h > class bstree { public: struct node { int data; node *left; node *right; }*head; void create (node *); void inorder (node *); void preorder (node *); void postorder (node *); }; void* bstree:: create(node *list) { node *temp1,*temp2; int val; if(list = = NULL) { list = new node; cout<<"nEnter Data Element:: "; cin>>list->data; list -> left = list -> right = NULL; } else
  • 23. { cout<<"n enter the data element"; cin>>val; temp1 = list; while( temp1 ! = NULL ) { temp2 = temp1; if(temp1 -> data > val) temp1 = temp1 -> left; else temp1 = temp1 -> right; } if(temp2 -> data > val) { temp2 -> left = new node; temp2 = temp2 -> left; temp2 -> data = val; temp2 -> left = temp2 -> right = NULL; } else { temp2 -> right = new node; temp2 = temp2 -> right; temp2 -> data = val; temp2 -> left = temp2 -> right = NULL; } } return (list); }
  • 24. void bstree:: inorder(node *root) { if( ! root ) return; inorder( root -> left ); cout<<root->data<<"t"; inorder( root -> right ); } void bstree::preorder(node*root) { if( ! root ) return; cout<<root->data<<”t”; preorder( root -> left ); preorder( root -> right); } void bstree::postorder(node*root) { if( ! root) return; postorder( root -> left ); postorder( root -> right ); cout<<root->data<<”t”; }
  • 25. void main ( ) { node n,*head; head = NULL; clrscr ( ); cout<<"nCreate A Binary Treen"; head=n.create ( head ); cout<<"n the inorder traversal gives the following nodes"; n.inorder ( head ); getch ( ); } OUTPUT:
  • 26.
  • 27. BINARY SEARCH TREE 15 7 22 A tree having left child less than parent and right child grater than the parent. Traversals are same as binary tree.
  • 28. SOURCE CODE: /* Program to implement Binary search tree */ #include < iostream.h > #include < conio.h > class btree { private : struct btreenode { btreenode *leftchild ; int data ; btreenode *rightchild ; } *root; public: btree ( ) ; void buildtree ( int num ) ; static void insert ( btreenode **sr, int num ) ; void traverse ( ) ; static void inorder ( btreenode *sr ) ; static void preorder ( btreenode *sr ) ; static void postorder ( btreenode *sr ) ; static void del ( btreenode *sr ) ; ~btree ( ) ; } ;
  • 29. btree :: btree ( ) { root = NULL ; } void btree :: buildtree ( int num ) { insert ( &root, num ) ; } void btree :: insert ( btreenode **sr, int num ) { if ( *sr == NULL ) { *sr = new btreenode ; ( *sr ) -> leftchild = NULL ; ( *sr ) -> data = num ; ( *sr ) -> rightchild = NULL ; return ; } else // search the node to which new node will be attached { // if new data is less, traverse to left if ( num < ( *sr ) -> data ) insert ( & ( ( *sr ) -> leftchild ), num ) ; else // else traverse to right insert ( & ( ( *sr ) -> rightchild ), num ) ; }r eturn ; }
  • 30. void btree :: traverse( ) { cout << "nIN - ORDER TRAVERSAL :: " ; inorder ( root ) ; cout << "nPRE - ORDER TRAVERSAL :: " ; preorder ( root ) ; cout << "nPOST - ORDER TRAVERSAL :: " ; postorder ( root ) ; } void btree :: inorder ( btreenode *sr ) { if ( sr != NULL ) { inorder ( sr -> leftchild ) ; cout << "t" << sr -> data ; inorder ( sr -> rightchild ) ; } else return ; } void btree :: preorder ( btreenode *sr ) { if ( sr != NULL ) { // print the data of a node cout << "t" << sr -> data ; // traverse till leftchild is not NULL preorder ( sr -> leftchild ) ; // traverse till rightchild is not NULL preorder ( sr -> rightchild ) ; }
  • 31. else return ; } void btree :: postorder ( btreenode *sr ) { if ( sr != NULL ) { postorder ( sr -> leftchild ) ; postorder ( sr -> rightchild ) ; cout << "t" << sr -> data ; } else return ; } btree :: ~btree( ) { del ( root ) ; } void btree :: del ( btreenode *sr ) { if ( sr != NULL ) { del ( sr -> leftchild ) ; del ( sr -> rightchild ) ; } delete sr ; }
  • 32. void main( ) { btree bt ; int req, i = 1, num ; clrscr(); cout << "n SPECIFY THE NUMBER OF ITEMS TO BE INSERTED :: " ; cin >> req ; while ( i + + <= req ) { cout << "n ENTER THE DATA :: " ; cin >> num ; bt.buildtree ( num ) ; } bt.traverse( ) ; getch(); } OUTPUT:
  • 33. SPARSE MATRIX AIM: Write a program in C++ to implement ADDITION and MULTIPLICTION of two SPARSE matrixes. THEORY: If a lot of elements from a matrix have a value 0 then the matrix is known as SPARSE MATRIX. If the matrix is sparse we must consider an alternate way of representing it rather the normal row major or column major arrangement. This is because if majority of elements of the matrix are 0 then an alternative through which we can store only the non-zero elements and keep intact the functionality of the matrix can save a lot of memory space. Example: Sparse matrix of dimension 7 x 7. COLUMNS 0 1 2 3 4 5 6 0 0 0 0 -5 0 0 0 1 0 4 0 0 0 0 7 2 0 0 0 0 9 0 0 ROWS 3 0 3 0 2 0 0 0 4 1 0 2 0 0 0 0 5 0 0 0 0 0 0 0 6 0 0 8 0 0 0 0
  • 34.
  • 35. SOURCE CODE: /*Program to demonstrate addition and multiplication of Two Sparse Matrix */ #include < iostream.h > #include < conio.h > #define x 25 class sparce { private: int a [ x ] [ x ], b [ x ] [ x ], c [ x ] [ x ], m, n, p, q; public: void init ( ); void input ( ); void add ( ); void mul ( ); void display ( int [25][25], int, int ); void convert( int [25][25], int, int ); }; void sparce :: init ( ) { int i, j; for(i = 0; i < x;i + + ) for( j = 0; j < x; j + +) c [ i ] [ j ] = 0; }
  • 36. void sparce :: input() { int i,j; cout<<"nEnter order Of First matrix::"; cin>>m>>n; cout<<"nEnter order Of Second matrix::"; cin>>p>>q; cout<<"nEnter"<<m*n<<"Elements Into First Matrixn"; for(i=0;i<m;i++) for( j = 0; j < n; j + + ) cin>> a[ i ] [ j ]; cout<<"nEnter"<<p*q<<"Elements Into Second Matrixn"; for(i = 0; i < p ; i + + ) for ( j = 0; j < q ; j + + ) cin>>b [ i ] [ j ]; } void sparce :: add ( ) { int i, j; if( m = = p && n = = q ) { for( i = 0 ; i < m ; i + + ) for( j = 0; j < n; j + + ) c[ i ] [ j ] = a [ i ][ j ] + b [ i ] [ j ]; convert( c, m, n); } else cout<<"nAddition Is Not Possible"; }
  • 37. void sparce :: mul ( ) { int i, j, k; if(n = = p) { for( i = 0; i < m; i + +) for( j = 0; j < q; j + + ) for( k = 0; k < n; k + + ) c[ I ] [ j ] + = a [ I ] [ k ] * b [ k ] [ j ]; convert(c, m, n); } else cout<<"n Multiplecation Is Not Possible"; } void sparce :: display(int c[25][25], int m, int n) { int i,j; for( i = 0 ;i < m; i + + ) { for( j = 0 ; j < n ; j + + ) cout<<c [ i ] [ j ]<<"t"; cout<<"n"; } }
  • 38. void sparce :: convert(int c[25][25], int m, int n) { int i, j, k = 1,t = 0; int sp[25][25]; for( i = 0 ; i < m ; i + +) for( j = 0 ; j < n ; j + + ) if(c [ i ] [ j ] ! = 0 ) { sp [ k ] [ 0 ] = i; sp [ k ] [ 1 ] = j; sp [ k ] [ 2 ] = c [ i ] [ j ]; k + + ; t + + ; } sp[ 0 ] [ 0 ] = m; sp[ 0 ] [ 1 ] = n; sp[ 0 ] [ 2 ] = t; display( sp, k, 3); } void main ( ) { sparce ob; clrscr ( ); ob.init ( ); ob.input ( ); cout<<"nAddition of Two Sparce Matrixn"; ob.add ( ); ob.init ( ); cout<<"nMultiplecation Of Two Sparce Matrixn"; ob.mul ( ); getch ( ); }
  • 40. INFIX TO POSTFIX CONVERTIONic  Suppose Q is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix expression P.  Step 1. Push “(“ onto stack and add “)” to the end of Q.  2. Scan Q from left to right and repeat step 3 to 6 for each element of Q until the stack is empty.  3. If an operand is encountered , add it to p.  4. If a left parenthesis is encountered ,push it onto stack.  5 If an operator * is encountered , then: a. repeatedly pop from stack and top each operator (on the top of stack ) which has the same precedence or higher precedence than * . b. Add * to stack.  6. If a right parenthesis is encountered , then: a. repeatedly from stack and add to P each operator (on the top of stack) until a left parenthesis is encountered. b. remove the left parenthesis [ Do not add the left parenthesis top] [End of if structure] [End of step 2 loop]  7. Exit
  • 41. Symbol scanned stack Expression P 1 A ( A 2 + ( + A 3 ( ( + ( A 4 B ( + ( AB 5 * ( + ( * AB 6 C ( + ( * ABC 7 - ( + ( - ABC* 8 ( ( + ( - ( ABC* 9 D ( + ( - ( ABC*D 10 / ( + ( - ( / ABC*D 11 E ( + ( - ( / ABC*DE 12 ^ ( + ( - ( / ^ ABC*DE 13 F ( + ( - ( / ^ ABC*DEF 14 ) ( + ( - ABC*DEF^/ 15 * ( + ( - * ABC*DEF^/ 16 G ( + ( - * ABC*DEF^/G 17 ) ( + ABC*DEF^/G*- 18 * ( + * ABC*DEF^/G*- 19 H ( + * ABC*DEF^/G*-H 20 ) ABC*DEF^/G*-H*+ (A+(B*C-(D/E^F)*G)*H)
  • 42. SOURCE CODE: /* Program To implement infix to postfix Expression */ #include < iostream.h > #include< process.h > #include < conio.h > char stack[30], postfix[30], infix[30]; int top = - 1; int pri( char x ) {i nt value; switch ( x ) { case ')': value=0; break; case '+': case '-': value=1; break; case '*': case '/': case '%': value=2; break; case '^': value=3; break; case '(': value=4; break; default: cout<<"INVALID EXPRESSION !!!!!!"; exit(1); } return value; }
  • 43. void push ( char x ) { top = top + 1; stack [top] = x; } char stacktop ( ) { return stack [ top ]; } int isalnum (char x) { return ( (x>='0' && x<='9') ||( x>='a' && x<='z') || ( x>='A' && x<='Z')); } char pop( ) { return stack[top - - ]; }
  • 44. void intopost(char infix[ ], char postfix[ ]) { int i, j=0; char c, pc; for ( i = 0; ( c = infix[ i ] ) != '0' ; i + +) { if ( isalnum (c) ) postfix [ j + + ] = c; else { while ( top ! = - 1 && (pri (stacktop () ) >= pri (c) ) ) { If ( stacktop( ) = = '(' && c! = ')' ) break; if ( stacktop( ) = = '(' && c = =')' ) { pop () ; break; } pc = pop( ); if ( pc! = '(' ) postfix [ j + + ] = pc; else break; } if( c! = ')' ) push ( c ); }} while( top ! = -1 ) postfix[ j + + ] = pop( ); postfix [ j ] = '0'; }
  • 45. void main ( ) { clrscr ( ); cout<<"ENTER INFIX EXPRESSION ::nnttt"; cin>>infix; intopost( infix, postfix ); cout<<"POSTFIX EXPRESSION ::nnttt "; cout<<postfix; getch ( ); } OUTPUT:
  • 46. POSTFIX EVALUATION THEORY: Reverse Polish notation is a mathematical notation wherein every operator follows all of its operands. It is also known as Postfix notation and is parenthesis free. In Reverse Polish notation the operators follow their operands; for instance, to add three and four, one would write “3 4 +” rather than “3 + 4”. If there are multiple operations, the operator is given immediately after its second operand; so the expression written “3 − 4 + 5” in conventional infix notation would be written “3 4 − 5 +” in RPN: first subtract 4 from 3, then add 5 to that. Infix Expression: Any expression in the standard form like "2*3-4/5" is an Infix(In order) expression. Postfix Expression: The Postfix(Post order) form of the above expression is "23*45/-". Postfix Evaluation: In normal algebra we use the infix notation like a+b*c. The corresponding postfix notation is abc*+. The algorithm for the conversion is as follows: •Scan the Postfix string from left to right. •Initialize an empty stack. •If the scanned character is an operand, add it to the stack. If the scanned character is an operator, there will be at least two operands in the stack If the scanned character is an Operator, then we store the top most element of the stack(topStack) in a variable temp. Pop the stack. Now evaluate topStack(Operator)temp. Let the result of this operation be retVal. Pop the stack and Push retVal into the stack. Repeat this step till all the characters are scanned. •After all characters are scanned, we will have only one element in the stack. Return topStack.
  • 47. Example: Postfix String: 1 2 3 * + 4 - . Initially the Stack is empty. Now, the first three characters scanned are 1,2 and 3, which are operands. Thus they will be pushed into the stack in that order. Stack Expression Next character scanned is "*", which is an operator. Thus, we pop the top two elements from the stack and perform the "*" operation with the two operands. The second operand will be the first element that is popped. Stack Expression The value of the expression(2*3) that has been evaluated(6) is pushed into the stack. Stack Expression
  • 48. Next character scanned is "+", which is an operator. Thus, we pop the top two elements from the stack and perform the "+" operation with the two operands. The second operand will be the first element that is popped. Stack Expression The value of the expression(1+6) that has been evaluated(7) is pushed into the stack. Stack Expression Next character scanned is "4", which is added to the stack. Stack Expression Next character scanned is "-", which is an operator. Thus, we pop the top two elements from the stack and perform the "-" operation with the two operands. The second operand will be the first element that is popped.
  • 49. The value of the expression(7-4) that has been evaluated(3) is pushed into the stack. Stack Expression The value of the expression(7-4) that has been evaluated(3) is pushed into the stack. Stack Expression Now, since all the characters are scanned, the remaining element in the stack (there will be only one End result: Postfix String : 1 2 3 * + 4 - Result : 3
  • 50. SOURCE CODE: /*Program To Evaluate Postfix Expression */ #include < iostream.h > #include < conio.h > #include < math.h > #include < string.h > class postfix { private: int stack[50], len, top; char post[50]; public: postfix ( ); void push ( int ); int pop ( ); int pfix ( ); }; void postfix :: postfix ( ) { top = - 1; }i nt postfix :: pfix ( ) { int a, b, i, temp; cout<<"nEnter Postfix Expression::"; cin>>post; len = strlen ( post ); post [ len] = '#';
  • 51. for( i = 0 ; post [ i ] ! = '#' ; i + +) { if( post [ i ] <= '9' && post [ i ] >= '0') push( post [ i ] - 48); else { a = pop ( ); b = pop ( ); switch ( post [ i ]) { case '+': temp = b + a; break; case '-': temp = b - a; break; case '*': temp = b * a; break; case '/': temp = b/a; break; case '%': temp = b%a; break; case '^': temp = pow( b, a ); } push ( temp ); } } return( pop ( ) ); }
  • 52. void postfix :: push( int x ) { stack[ + + top ] = x; }i nt postfix :: pop ( ) { int x = stack [ top ]; top- -; return x; } void main ( ) { int x; postfix ob; clrscr ( ); x=ob.pfix ( ); cout<<"nResult Of Postfix Expression Ist"<<x; getch ( ); } OUTPUT:
  • 53. Quick Sort 11 7 21 3 46 89 2 34 right 1)When pivot is at left end, 1)Compare a[pivot] with a[right] element if (a[pivot] < a[right]) then right-- else swap a[pivot] and a[right] 2)When pivot is at right end, Compare a[pivot] with a[left] element if (a[left] < a[pivot]) then left++ else swap a[left] and a[pivot] pivot left
  • 54. STEP1: 11 7 21 3 46 89 2 34 left, pivot right STEP2: 2 7 21 3 46 89 11 34 left right, pivot STEP3: 2 7 21 3 46 89 11 34 left right, pivot STEP4: 2 7 21 3 46 89 11 34 left right, pivot STEP5: 2 7 11 3 46 89 21 34 left, pivot right STEP6: 2 7 11 3 46 89 21 34 left, pivot right
  • 55. STEP7: 2 7 11 3 46 89 21 34 left, pivot right STEP8: 2 7 11 3 46 89 21 34 left, pivot right STEP9: 2 7 3 11 46 89 21 34 left right, pivot STEP10: 2 7 3 11 46 89 21 34 left, right, pivot  Here we will stop the main process as the left and right pointers are equal.  Now see the elements left to ‘11’ are less than ‘11’ and elements right to ‘11’ are grater than ‘11’.  Now divide the main list into 2 sub lists such as(2,7,3) and (46,89,21,34) and do the same above process.
  • 56.  #include<stdio.h> #include<conio.h> #define MAXSIZE 500 Source code void quickSort(int elements[], int maxsize); void sort(int elements[], int left, int right); int elements[MAXSIZE]; int main() { int i, maxsize; printf(“nHow many elements you want to sort: “); scanf(“%d”,&maxsize); printf(“nEnter the values one by one: “); for (i = 0; i < maxsize; i++) { printf (“nEnter element %i :”,i); scanf(“%d”,&elements[i]); }
  • 57. printf(“nArray before sorting:n”); for (i = 0; i < maxsize; i++) printf(“[%i], “,elements[i]); printf (“n”); quickSort(elements, maxsize); printf(“nArray after sorting:n”); for (i = 0; i < maxsize; i++) printf(“[%i], “, elements[i]); } void quickSort(int elements[], int maxsize) { sort(elements, 0, maxsize - 1); } void sort(int elements[], int left, int right) { int pivot, l, r; l = left; r = right; pivot = elements[left]; while (left < right) { while ((elements[right] >= pivot) && (left < right)) right—;
  • 58. if (left != right) { elements[left] = elements[right]; left++; } while ((elements[left] <= pivot) && (left < right)) left++; if (left != right) { elements[right] = elements[left]; right—; }} elements[left] = pivot; pivot = left; left = l; right = r; if (left < pivot) sort(elements, left, pivot - 1); if (right > pivot) sort(elements, pivot + 1, right); }
  • 59.  Consider the elements as shown, 77 33 44 11 88 22 66 55 77 0 Selection sort min i  Here min is compared with a[1]  as min is > a[1]  min=a[1] 33 0 min i  This min is compared with a[2] ,as this is < a[2]  min is same that is 33  This min is compared with a[3] ,as this is > a[3]  min =a[3]. 11 0 min I  Now this is compared with a[4],a[5],a[6],a[7] as min is less than all of these min remains 33  At last swap min and a[i] like this continue the process with i=1,2,3……
  • 60. SOURCE CODE: #include < iostream.h > #include < conio.h > class selsort {public : void sort(int *, int); }; void selsort::sort(int *a, int n) { int i, j, x, min, temp; for( i = 0 ; i < ( n – 1 ) ; i + + ) { x = i; min = a [ i ]; for( j = i + 1; j < n; j + + ) {i f( min > a [ j ] ) { min = a [ j ]; x = j; }} temp = a [ i ] ; a [ i ] = a [ x ]; a [ x ] = temp; }} void main( ) {int a[50], n, i; clrscr( );
  • 61. cout<<"n ENTER THE SIZE OF THE ARRAY: nt "; cin>>n; cout<<"n ENTER THE ELEMENTS:nt"; for( i = 0 ;i < n ;i + + ) cin>>a [ i ]; cout<<"n ELEMENTS BEFORE SORTING:nt"; for( i = 0 ; i < n ; i + + ) cout<<a[i]<<"t"; selsort obj; obj.sort(a,n); cout<<"n ELEMENTS AFTER SORTING ARE:nt"; for( i = 0 ; i < n ; i + + ) cout<<a[i]<<"t"; getch(); } OUTPUT:
  • 62. LINEAR SEARCH 10 20 30 40 50 60 70 0 1 2 3 4 5 6 •Here we want to search for ‘50’. • So compare ’50’ with a[i] where i=0,1,2,3,…. If (a[i]==50) Then element is found at location i that is 4 Else i++ •Here the time complexity is O(n).
  • 63. SOURCE CODE: #include < iostream.h > #include < conio.h > class lsearch { private: int a[50], n, count, key; public: void init ( ); void linear ( ); }; void lsearch::init ( ) { count = 0; } void lsearch::linear ( ) { int i; clrscr ( ); cout<<"nENTER SIZE OF AN ARRAY :: "; cin>>n; cout<<"nnENTER "<<n<<" ELEMENTS INTO AN ARRAY ::"; for( i = 0; i < n; i + +) cin>> a [ i ]; cout<<"nnENTER SEARCH ELEMENT :: "; cin>>key; cout<<"nnELEMENTS IN ARRAY ARE :n";
  • 64. for( i = 0; i < n; i + +) cout<< a [ i ]<<"t"; for( i = 0; i < n; i + + ) if(a [ i ] = = key) { count + +; break; }i f( count = = 1 ) cout<<"nn ELEMENT IS FOUND IN "<< ( i + 1)<<" LOCATION"; else cout<<"nELEMENT IS NOT FOUND...."; } void main ( ) { lsearch ob; clrscr ( ); ob.init (); ob.linear ( ); getch ( ); }
  • 66. BINARY SEARCH •Here elements must be in Ascending/Descending order. •Consider the elements in ascending order 711 15 23 46 64 71 83 low high here low=0 and high=7 Then calculate mid=(low+high)/2 •Let us search for k=71 •If (a[mid]==k) then element is found at ‘mid’ location •If(k<a[mid]) then high=mid-1 else low=mid+1 •Repeat the previous steps tell low and high are equal.
  • 67. SOURCE CODE: /*Program To Implement Binary Search */ #include < iostream.h > #include < conio.h > class bsearch { private : int a[50], n , x; public : void binary ( ); }; void bsearch::binary ( ) { int i, j, temp, mid, beg, end; beg = 0; cout<<"nnENTER THE SIZE OF THE ARRAY :: "; cin>>n; end = n - 1; cout<<"nnENTER THE ELEMENTS OF THE ARRAY :: "; for( i = 0; i < n; i + +) cin>>a[i]; cout<<"nnELEMENTS BEFORE BEFORE SORTING ARE :: "; for( i = 0; i < n; i + + ) cout<< a [ i ]<<" ";
  • 68. for( i = 0; i < n; i + + ) { for( j = i + 1; j < n; j + +) { if( a[ i ] > a[ j ] ) { temp = a [ i ]; a[ i ] = a[ j ]; a[ j ] = temp; } } } cout<<"nnELEMENTS AFTER SORTING ARE :: "; for( i = 0; i < n; i + + ) cout<<a[ i ]<<" "; cout<<"nnENTER THE ELEMENT TO BE SEARCHED :: "; cin>>x; while ( beg < = end ) { mid = ( beg + end ) / 2; if ( a [ mid ] = = x ) {
  • 69. cout<<"nSEARCHING IS SUCCESSFUL AND THE ELEMENTS IS PRESENT AT "<< ( mid + 1 )<<" LOCATION"; return; } else if(x<a[mid]) end = mid - 1; else beg = mid + 1; } cout<<"n SEARCH IS UNSUCCESSFUL"; } void main ( ) { bsearch obj; clrscr ( ); obj . binary ( ); getch ( ); } OUTPUT:
  • 70. POLINOMIAL ADDITION AND MULTIPLICATION •1 expression: 3x2+2x+1 Store all the coefficients 1,2,3 into an array1. •1 expression: 2x2+1x+2 Store all the coefficients 2,1,2 into an array2. ADDITION: 3x2+2x+1 2x2+1x+2 5x2+3x+3 Store the result expression coefficients in array3
  • 71. SOURCE CODE: /*Program To Demonstrate Addition And Multiplication Of Two Polynomial Expression */ #include < iostream.h > #include < conio.h > #define n 100 class poly { private: int a[n], b[n], add[n], mul[n], p, q, at; public: void init ( ); void input ( ); void process ( ); void display ( ); }; void poly :: init ( ) { int i; for( i = 0; i < n; i + + ) a[ i ] = b [ i ] = add[ i ] = mul[ i ] = 0; }
  • 72. void poly :: input ( ) { int i; cout<<"nEnter Degree Of First Polynomial::"; cin>>p; cout<<"nEnter Degree Of Second Polynomial::"; cin>>q; cout<<"nEnter Values First Polynomialn"; for( i = 0; i <= p; i + + ) { cout<<"nEnter X^"<<i<<" Th Coefficient"; cin>>a[ i ]; } cout<<"nEnter Values First Polynomialn"; for( i = 0; i <= q; i + + ) { cout<<"nEnter X^"<<i<<" Th Coefficient"; cin>>b[ i ]; } }
  • 73. void poly :: process ( ) { int i, j; if( p > q ) at = p; else at = q; for ( i = 0; i <= at; i + +) add[ i ] = a[ i ] + b[ i ]; for( i = 0; i <= p; i + + ) for( j = 0; j <= q; j + + ) mul [ i + j ] + = a [ i ] * b [ j ]; } void poly :: display ( ) { int i; cout<<"Addition Of Two Polynomial Expressions Arenn"; for( i = at; i >=0 ; i - -) cout<<add[i]<<"X^"<<i<<"+"; cout<<"nnMultiplecation Of Two Polynomial Expressions Arenn"; for( i = p + q; i > = 0; i - -) cout<<mul[i]<<"X^"<< i <<"+"; }
  • 74. void main() { poly ob; clrscr ( ); ob.init ( ); ob.input ( ); ob.process ( ); ob.display ( ); getch ( ); } OUTPUT:
  • 75. SINGLE LINKED LIST THEORY: Figure shows a Linked List. Each item in the list is called a node and contain two fields, a data field and a next address field. The data field holds the actual element on the list. The next address field contains the address of the next node in the list. Such an address which is used to access a particular node, is known as a pointer. The entire linked list is accesses from an external pointer list, that points to the first node in the list. The next field of last node in the list contains a special value, known as NULL. The null pointer is used to signal the end of the list. The singly-linked list is the most basic of all the linked data structures. A singly-linked list is simply a sequence of dynamically allocated objects, each of which refers to its successor in the list. Despite this obvious simplicity, there are myriad implementation variations. The following code inserts a node after an existing node in a singly linked list. The diagram shows how it works. Inserting a node before an existing one cannot be done; instead, you have to locate it while keeping track of the previous node.
  • 76. Similarly, we have functions for removing the node after a given node, and for removing a node from the beginning of the list. The diagram demonstrates the former. To find and remove a particular node, one must again keep track of the previous element.
  • 77. SOURCE CODE: /*Program To Implement Single Linked list */ #include< stdio.h > #include < iostream.h > #include < conio.h > #include < process.h > #include< alloc.h > class slist { private: struct list {i nt data; struct list *next; }*start,*temp,*curr,*add,*tem,*addr; public: void init ( ); void create ( ); void disp ( ); list *search ( int ); void insert ( ); void del ( ); };
  • 78. void slist :: init ( ) { start = temp = curr = NULL; } void slist::create ( ) { char ch; temp = new list; cout<<"n ENTER THE DATA TO BE STORED n"; cin>> temp->data; temp->next = NULL; start = curr = temp; cout<<"n DO YOU WANT TO INSERT ANOTHER NODE (Y/N)"; cin>>ch; while( ch = = 'y' ) { temp = new list; cout<<"n ENTER DATA TO BE STORED:n"; cin>>temp->data; temp->next = NULL; curr->next = temp; curr = temp; cout<<"n DO YOU WANT TO INSERT ANOTHER NODE (Y/N):"; cin>>ch; } }
  • 79. void slist :: disp ( ) { if( start = = NULL) cout<<"n LIST IS EMPTY"; else { cout<<"n DATA PRESENT IN A LIST IS n"; temp = start; while( temp -> next ! = NULL) { cout<<"|"<<temp->data<<"|"<<temp->next<<"|-->"; temp = temp -> next; } cout<<"|"<<temp->data<<"|"<<temp->next<<"|"; } } slist::list *slist :: search( int key) { temp = start; while( temp -> next ! = NULL) { if( temp->data = = key ) return temp; else temp = temp->next; }i f( temp->next = = NULL )
  • 80. if( temp->data = = key ) return temp; else return NULL; } void slist:: insert ( ) { int key; cout<<"n ENTER DATA AFTER WHICH WE CAN INSERT NEW NODE:"; cin>>key; add=search(key); if( add = = NULL ) cout<<"n NODE IS NOT FOUND"; else { temp = new list; cout<<"n ENTER INSERTED ELEMENT"; cin>>temp->data; if( add->next = = NULL) { temp->next = NULL; add->next = temp; curr = temp; }
  • 81. else { addr = add->next; add->next = temp; temp->next = addr; } } } void slist :: del ( ) { int key; cout<<"n ENTER NODE DATA SHOULD BE DELETE:n"; cin>>key; add = search ( key ); if( add = = NULL ) cout<<"n NODE IS NOT FOUNDn"; else if( curr = = add ) { curr = start; while( curr->next ! = NULL) { temp = curr; curr = curr->next; }
  • 82. free ( curr ); curr = temp; curr->next = NULL; } else if( start = = add ) { temp = start; start = start->next; free( temp ); } else { tem = add->next; temp = start; while( temp-> next ! = add) temp = temp->next; temp->next = tem; free( add ); } } void main ( ) { slist ob; int key, ch; list *temp; clrscr ( ); cout<<"n * * * SINGLE LINKED LIST OPERATION * * * n";
  • 83. cout<<"n 1. CREATE n 2. DISPLAY n 3. INSERT n 4. DELETE n 5. SEARCH n 6.EXIT n"; cout<<"n *************************n"; do { cout<<"n ENTER YOUR CHOICE n"; cin>>ch; switch ( ch ) { case 1: ob.create ( ); break; case 2: ob.disp ( ); break; case 3: ob.insert ( ); break; case 4: ob.del ( ); break; case 5: cout<<"n ENTER THE ELEMENT TO SEARCH"; cin>>key; temp=ob.search(key); if( temp = = NULL) cout<<"n ELEMENT IS NOT FOUND n"; else cout<<"n ELEMENT IS FOUND n"; break; case 6: exit(0); default: cout<<"n INVALID CHOICE n"; } }while( ch ! = 0 ); getch ( ); }
  • 85. SINGLE CIRCULAR LINKED LIST THEORY: The linked list that we have seen so far is often know as linear lists. The elements of such a linked list can be accessed, first by setting up a pointer pointing to the first node in the list and then traversing the entire list using this pointer. Although a linear linked list is a useful data structure, it has several shortcomings.
  • 86. SOURCE CODE: /* Program to implement single circular linked list */ #include<iostream.h> #include<conio.h> #include<process.h> #include<alloc.h> class clist { private: struct list { int data; struct list *next; }*start,*temp,*curr,*add,*tem,*addr; public: void init(); void creat(); void display(); list *search(int); void insert(); void del(); }; void clist::init() { start=temp=curr=NULL; }
  • 87. void clist::creat() { char ch; temp=new list; cout<<"n ENTER ENTER DATA TO BE STORED ::"; cin>>temp->data; cout<<"nADDRESS OF STARTING NODE :: "<<temp; temp->next=start; start=curr=temp; cout<<"nDO YOU WANT TO INSERT ANOTHER NODE (y/n) :: "; cin>>ch; while(ch=='y') { temp=new list; cout<<"n ENTER DATA TO BE STORED :: "; cin>>temp->data; temp->next=start; curr->next=temp; curr=temp; cout<<"nDO YOU WANT TO INSERT ANOTHER NODE (y/n) :: "; cin>>ch; } }
  • 88. void clist::display() { if(start==NULL) cout<<"nLIST IS EMPTY....."; else cout<<"nDATA PRESENT IN A LIST IS :: n"; temp=start; while(temp->next!=start) { cout<<"|"<<temp->data<<"|"<<temp->next<<"|-->"; temp=temp->next; } cout<<"|"<<temp->data<<"|"<<temp->next<<"|"; } clist::list *clist::search(int key) { temp=start; while(temp->next!=start) { if(temp->data==key) return temp; else temp=temp->next; }
  • 89. if(temp->next==NULL) { if(temp->data==key) return temp; else return NULL; } return NULL; } void clist::insert() { int key; cout<<"n ENTER DATA AFTER WHICH WE CAN INSERTED NEW NODE :: "; cin>>key; add=search(key); if(add==NULL) cout<<"n NODE IS NOT FOUND ...."; else { temp=new list; cout<<"n ENTER INSERTED ELEMENT :: "; cin>>temp->data;
  • 90. if(add->next==start) { temp->next=start; add->next=temp; curr=temp; } else { addr=add->next; add->next=temp; temp->next=addr; } } } void clist::del() { int key; cout<<"nEnter node to deleted:"; cin>>key; add=search(key); if(add==NULL) cout<<"nNode is not found"; else if(curr==add)
  • 91. { curr=start; while(curr->next!=start) { temp=curr; curr=curr->next; } free(curr); curr=temp; curr->next=start; } else if(start==add) { temp=start; start=start->next; free(temp); } else { tem=add->next; temp=start; while(temp->next!=add) temp=temp->next; temp->next=tem; free(add); } }
  • 92. void main() { clist ob; int key,ch; clist::list *temp; clrscr(); cout<<"nCIRCULAR LINKED LIST n"; cout<<"n1.Createn2.Displayn3.Insertn4.Deleten5.Searchn6.Exitn"; do { cout<<"nEnter your choice"; cin>>ch; switch(ch) { case 1:ob.creat(); break; case 2:ob.display(); break; case 3:ob.insert(); break; case 4:ob.del(); break;
  • 93. case 5:cout<<"nEnter search element"; cin>>key; temp=ob.search(key); if(temp==NULL) cout<<"nElement is not found"; else cout<<"nElement is found"; break; case 6:exit(0); default:cout<<"Invalid choice"; } }while(ch!=6); getch(); }
  • 95. DOUBLE LINKED LIST AIM: Write a program in C++ to implement DOUBLE LINKED LIST THEORY: A two-way list is a linear collection of data elements, called nodes, where each node N is divided into three parts: •An item data field. •A pointer field next which contains the location of the next node in the list. •A pointer field prev which contains the location of the previous node in the list. The list requires two list pointer variables: FIRST, which points to the first node in the list, and LAST, which points to the last node in the list. The figure contains a schematic diagram of such a list. Observe that the null pointer appears in the next field of the last node in the list and also in the prev field of the first node in the list. Observe that, using the variable FIRST and the pointer field next, we can traverse a two-way list in the forward direction as before. On the other hand, using the variable LAST and the pointer field prev, we can also traverse the list in the backward direction.
  • 96. OPERATION ON TWO-WAY LISTS: 1. Traversing. 2. Searching. 3. Deleting 4Inserting
  • 97. SOURCE CODE: /* Program to implement Double linked list */ #include<iostream.h> #include<conio.h> #include<process.h> #include<alloc.h> class dlist { private: struct list { int data; struct list *next,*prev; }*start,*temp,*curr,*add,*addr,*tem; public: void init(); void creat(); void display(); list *search(int); void insert(); void del(); }; void dlist::init() { start=temp=curr=NULL; }
  • 98. void dlist::creat() { char ch; temp=new list; cout<<"nENTER DATA TO BE STORED :: "; cin>>temp->data; cout<<"n STARTING NODE ADDRESS :: "<<temp<<"n"; temp->next=NULL; temp->prev=NULL; start=curr=temp; cout<<"n DO YOU WANT TO INSERT ANOTHER NODE (y/n) :: "; cin>>ch; while(ch=='y') { temp=new list; cout<<"nENTER DATA TO BE STORED :: "; cin>>temp->data; temp->next=NULL; temp->prev=curr; curr->next=temp; curr=temp; cout<<"nDO YOU WANT TO INSERT ANOTHER NODE (y/n) :: "; cin>>ch; } }
  • 99. void dlist::display() { if(start==NULL) cout<<"n LIST IS EMPTY...."; else { cout<<"n DATA PRESENT IN A LISTn:::"; temp=start; while(temp->next!=NULL) { cout<<"|"<<temp->prev<<"|"<<temp->data<<"|"<<temp->next<<"|-- >"; temp=temp->next; } cout<<"|"<<temp->prev<<"|"<<temp->data<<"|"<<temp->next<<"|"; } } dlist::list *dlist::search(int key) { temp=start; while(temp->next!=NULL) { if(temp->data==key)
  • 100. return temp; else temp=temp->next; }i f(temp->next==NULL) { if(temp->data==key) return temp; else return NULL; } return NULL; } void dlist::insert() { int key; cout<<"nENTER DATA AFTER WHICH WE CAN INSERT A NEW NODE :: "; cin>>key; add=search(key); if(add==NULL) cout<<"n NODE IS NOT FOUND....."; else tem=new list;
  • 101. cout<<"n ENTER ELEMENT TO BE SEARCHED :: "; cin>>tem->data; if(add->next==NULL) { tem->next=NULL; tem->prev=add; add->next=tem; curr=tem; } else { addr=add->next; add->next=tem; tem->next=addr; tem->prev=add; } } void dlist::del() { int key; cout<<"n ENTER NODE DATA TO BE DELETED :: "; cin>>key; add=search(key); if(add==NULL) cout<<"n NODE IS NOT FOUND :: "; else
  • 102. if(curr==add) { curr=start; while(curr->next!=NULL) { temp=curr; curr=curr->next; } free(curr); curr=temp; curr->next=NULL; } else if(start==NULL) { temp=start; start=start->next; free(temp); } else { tem=add->next; temp=start; while(temp->next!=add) temp=temp->next; temp->next=tem; free(add); } }
  • 103. void main() { dlist ob; int key,ch; dlist::list *temp; clrscr(); cout<<"**********DOUBLE LINKED LIST**********"; cout<<"n1.Createn2.Displayn3.Insertn4.Deleten5.Searchn6.Exitn"; do { cout<<"nENTER YOUR CHOICE :: "; cin>>ch; switch(ch) { case 1:ob.creat(); break; case 2:ob.display(); break; case 3:ob.insert(); break; case 4:ob.del(); break;
  • 104. case 5:cout<<"n ENTER SEARCH ELEMENT :: "; cin>>key; temp=ob.search(key); if(temp==NULL) cout<<"n ELEMENT IS NOT FOUND...."; else cout<<"n ELEMENT IS FOUND....."; break; case 6:exit(0); default:cout<<"n INVALID CHOICE...."; } }while(ch!=6); getch(); }
  • 106. GRAPH TRAVERSING: DEPTH FIRST SEARCH THEORY: •DFS is an uninformed search that progresses by expanding the first child node of the search tree that appears and thus going deeper and deeper until a goal node is found, or until it hits a node that has no children. Then the search backtracks, returning to the most recent node it hadn't finished exploring. In a non-recursive implementation, all freshly expanded nodes are added to a LIFO stack for exploration. •Space complexity of DFS is much lower than BFS (breadth-first search). It also lends itself much better to heuristic methods of choosing a likely-looking branch. Time complexity of both algorithms are proportional to the number of vertices plus the number of edges in the graphs they traverse (O(|V| + |E|)).
  • 107. SOURCE CODE: /*Program To Implement Depth First Search */ #include < iostream.h > #include < conio.h > #define MAX 20 class depth { private: int a[MAX][MAX], visited[MAX]; int n, top; public: void init ( ); void input ( ); void dfs ( int ); }; void depth::init ( ) { int i, j; for( i = 0; i < MAX; i + + ) { visited[ i ] = 0; for( j =0; j < MAX ; j + + ) a[ i ] [ j ] = 0; } top = - 1; } void depth::input ( ) { int i, j; cout<<"nENTER NUMBER OF NODES IN A GRAPH :: ";
  • 108. cin>>n; cout<<"nENTER ADJACENCY MATRIX FOR A GRAPH :: n"; for( i = 1; i <= n; i + +) for( j = 1; j <= n; j + + ) cin>>a[ i ][ j ]; } void depth::dfs ( int v) { int i; visited[v] = 1; cout<<v<<"->"; for( i = 1; i <= n; iI + + ) if( a [ v ] [ i ] = = 1 && visited [ i ] = = 0) dfs ( i ); } void main ( ) { depth ob; int start; clrscr ( ); ob.init ( ); ob.input ( ); cout<<"nSTARTING NODE FOR DFS TRAVERSING :: "; cin>>start; cout<<"nDEPTH FIRST SEARCH TRAVERSING IS ::nn"; ob.dfs ( start ); getch ( ); }
  • 110. GRAPH TRAVERSING: BREADTH FIRST THEORY: •BFS is an uninformed search method that aims to expand and examine all nodes of a graph or combinations of sequence by systematically searching through every solution. In other words, it exhaustively searches the entire graph or sequence without considering the goal until it finds it. •From the standpoint of the algorithm, all child nodes obtained by expanding a node are added to a FIFO queue. In typical implementations, nodes that have not yet been examined for their neighbors are placed in some container (such as a queue or linked list) called "open" and then once examined are placed in the container "closed". Algorithm for Breadth First Search 1.Enqueue the root node. 2.Dequeue a node and examine it. •If the element sought is found in this node, quit the search and return a result. •Otherwise enqueue any successors (the direct child nodes) that have not yet been discovered. 3.If the queue is empty, every node on the graph has been examined – quit the search and return "not found". 4.Repeat from Step 2.
  • 111. SOURCE CODE: /*Program To Implement Breadth First Search */ #include < iostream.h > #include < conio.h > #define MAX 20 class breadth { private: int a[MAX][MAX], visited[MAX], queue[50]; int n, front, rear; public: void init ( ); void input ( ); void bfs ( ); }; void breadth::init ( ) { int i, j; for( i = 0; i < MAX; i + + ) { visited [ i ] = 0; for( j = 0; j < MAX; j + + ) a[ i ] [ j ] = 0; } front = rear = - 1; }
  • 112. void breadth::input ( ) { int i, j; cout<<"nENTER NUMBER OF NODES IN A GRAPH :: "; cin>>n; cout<<"nENTER ADJACENCY MATRIX FOR A GRAPH :: n"; for( i = 1;i <= n; i + + ) for( j = 1; j <= n; j + + ) cin>>a[ i ][ j ]; } void breadth::bfs ( ) { int i, start; cout<<"nSTARTING NODE FOR BFS TRAVERSING :: "; cin>>start; cout<<"n BREADTH FIRST SEARCH TRAVERSING IS:: n t"; cout<<start; visited[ start ] = 1; rear + +; front + +; queue[ rear ] = start; while(front <= rear) { start = queue[front]; front + +;
  • 113. for( i =1; i <= n; i + + ) { if(a[ start ][ i ] = =1 && visited[ i ] = = 0) { cout<<"->"<<i; visited[ i ] =1; rear + +; queue [ rear ] = i; } } } } void main ( ) { breadth ob; int start; clrscr ( ); ob.init ( ); ob.input ( ); ob.bfs ( ); getch ( ); }
  • 115. SHORTEST PATH FOR GRAPH THEORY: Shortest path is nothing but the path which lies between two nodes with the lowest cost. In a graph contain so many paths are existed between two nodes (source node to destination node) to choose the lowest cost path to reach from source node to destination node is nothing but shortest path algorithm. Shortest path algorithm was first proposed by E. W. DIJKSTRA. SOURCE CODE: /*Program To Implement Shortest Path for Graph */ #include < iostream.h > #include < conio.h > #define INF 9999 class stpath { private: int i, j, k; public: void spath(int [ ][20], int ); void display(int [ ][20], int ); };
  • 116. void stpath::spath(int a[ ][20], int n) { for( i = 0 ;i < n; I + + ) for( j = 0; j < n; j + + ) if(a[ i ] [ j ] = = 0) a[ i ][ j ] = INF; cout<<"nADJACENCY MATRIX OF COST OF EDGES ARE ::"; display( a, n ); for( k = 0; k < n; k + + ) for( i = 0; i < n; i + + ) for( j = 0; j < n; j + + ) if( a[ i ][ j ] > a[ i ] [ k] + a[ k ][ i ]) a[ i ][ j ] = a[ i ][ k ] + a[ k ][ j ]; cout<<"nADJACENCY MATRIX OF LOWEST COST OF EDGES ARE ::n"; display(a, n); } void stpath::display(int a[ ] [20], int n) { for( i = 0; i < n; i + + ) { for( j = 0; j < n; j + + ) cout<<a[ i ][ j ]<<"t"; cout<<"n"; } }
  • 117. void main() { int i, j , n , a[20][20]; stpath ob; clrscr(); cout<<"nENTER NUMBER OF NODES IN A GRAPH :: "; cin>>n; cout<<"nENTER ADJACENCY MATRIX ::n"; for( i = 0; i < n; i + + ) for( j = 0; j < n; j + + ) { cout<<"Enter "<<i+1<<" To "<<j+1<<" Node Distance"; cin>>a[ i ] [ j ]; } ob.spath(a, n); getch ( ); }