0% found this document useful (0 votes)
265 views61 pages

DS Lab Manual

The document describes three C programs to: 1. Add two polynomials represented using circular linked lists and print the resulting polynomial. 2. Convert a valid infix arithmetic expression to postfix notation and print both expressions. 3. Evaluate a valid postfix expression using a stack.

Uploaded by

Hemu Sava
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
265 views61 pages

DS Lab Manual

The document describes three C programs to: 1. Add two polynomials represented using circular linked lists and print the resulting polynomial. 2. Convert a valid infix arithmetic expression to postfix notation and print both expressions. 3. Evaluate a valid postfix expression using a stack.

Uploaded by

Hemu Sava
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

1. Using circular representation for a polynomial, design, develop, and execute a program in C to
accept two polynomials, add them, and then print the resulting polynomial.
Description:
A Polynomial is can be expressed in terms that only have positive integer exponents and the operations
of addition, subtraction, and multiplication.
A polynomial equation is an equation that can be written in the form
axn + bxn-1 + . . . + r x + s = 0, where a, b, . . . , r and s are constants.
We call the largest exponent of x appearing in a non-zero term of a polynomial the degree of that
polynomial.
Examples
1. 3x + 1 = 0 has degree 1, since the largest power of x that occurs is x = x1. Degree 1 equations are called
linear equations.
2. x2 - x - 1 = 0 has degree 2, since the largest power of x that occurs is x2. Degree 2 equations are also
called quadratic equations, or just quadratics.
3. x3 = 2x2 + 1 is a degree 3 polynomial (or cubic) in disguise. It can be rewritten as x3 - 2x2 - 1 = 0,
which is in the standard form for a degree 3 equation.
4. x4 - x = 0 has degree 4. It is called a quartic.
Simplify (3x3 + 3x2 4x + 5) + (x3 2x2 + x 4)
Can be added horizontally:
(3x3 + 3x2 4x + 5) + (x3 2x2 + x 4)
= 3x3 + 3x2 4x + 5 + x3 2x2 + x 4
= 3x3 + x3 + 3x2 2x2 4x + x + 5 4
= 4x3 + 1x2 3x + 1
...or vertically:

Program:
#include<malloc.h>
#include<conio.h>
#include<stdio.h>
struct link
{
int coeff;
Dept of Information Science & Engineering, SCE

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


int pow;
struct link*next;
};
struct link *poly1=NULL, *poly2=NULL, *poly=NULL;
void create(struct link*node)
{
char ch;
do
{
printf("\n enter coeff:");
scanf("%d",&node->coeff);
printf("\n enter power:");
scanf("%d",&node->pow);
node->next=(struct link*)malloc(sizeof(struct link));
node=node->next;
node->next=NULL;
printf("\n continue(y/n):");
ch=getch();
}
while(ch=='y'||ch=='Y');
}
void show(struct link*node)
{
while(node->next!=NULL)
{
printf("%dx^%d",node->coeff,node->pow);
node=node->next;
if(node->next!=NULL)
printf("+");
}
}
void polyadd(struct link*poly1,struct link*poly2,struct link*poly)
{
while(poly1->next&&poly2->next)
{
if(poly1->pow>poly2->pow)
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;

Dept of Information Science & Engineering, SCE

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


}
else if(poly1->pow<poly2->pow)
{
poly->pow=poly2->pow;
poly->coeff=poly2->coeff;
poly2=poly2->next;
}
else
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff+poly2->coeff;
poly1=poly1->next;
poly2=poly2->next;
}
poly->next=(struct link*)malloc(sizeof(struct link));
poly=poly->next;
poly->next=NULL;
}
while(poly1->next||poly2->next)
{
if(poly1->next)
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;
}
if(poly2->next)
{
poly->pow=poly2->pow;
poly->coeff=poly2->coeff;
poly2=poly2->next;
}
poly->next=(struct link*)malloc(sizeof(struct link));
poly=poly->next;
poly->next=NULL;
}
}

Dept of Information Science & Engineering, SCE

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


void main()
{
clrscr();
char ch;
do
{
poly1=(struct link*)malloc(sizeof(struct link));
poly2=(struct link*)malloc(sizeof(struct link));
poly=(struct link*)malloc(sizeof(struct link));
printf("\n enter 1st number:");
create(poly1);
printf("\n enter 2nd number:");
create(poly2);
printf("\n 1st number:");
show(poly1);
printf("\n 2nd number:");
show(poly2);
polyadd(poly1,poly2,poly);
printf("\n added polynomial:");
show(poly);
printf("\n add two more numbers: y/n ");
ch=getch();
}
while(ch=='y'||ch=='Y');
}

Sample Output
enter 1st number:
enter coeff:4
enter power:3
continue(y/n):y
enter coeff:
2
enter power:3
continue(y/n):y
Dept of Information Science & Engineering, SCE

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


enter 2nd number:
enter coeff: 2
enter power:4
continue(y/n):y
1st number: 4x^3+2x^3
2nd number: 2x^4
added polynomial:2x^4+4x^3+2x^3
add two more numbers: y/n : n

Dept of Information Science & Engineering, SCE

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


2. Design, develop, and execute a program in C to convert a given valid parenthesized infix
arithmetic expression to postfix expression and then to print both the expressions. The expression
consists of single character operands and the binary operators + (plus), - (minus), * (multiply) and /
(divide).
Description:
Infix Expression : Any expression in the standard form like "2*3-4/5" is an Infix(Inorder) expression,
where operator is between its 2 operands.
Postfix Expression : The Postfix(Postorder) form of the above expression is "23*45/-", where operator
is placed after its 2 operands.
Infix to Postfix Conversion :
The algorithm for the conversion is as follows :

Scan the Infix string from left to right.


Initialise an empty stack.
If the scannned character is an operand, add it to the Postfix string. If the scanned character is an
operator and if the stack is empty Push the character to stack.
If the scanned character is an Operand and the stack is not empty, compare the
precedence of the character with the element on top of the stack (topStack). If topStack
has higher precedence over the scanned character Pop the stack else Push the scanned
character to stack. Repeat this step as long as stack is not empty and topStack has
precedence over the character.
Repeat this step till all the characters are scanned.

(After all characters are scanned, we have to add any character that the stack may have to the
Postfix string.) If stack is not empty add topStack to Postfix string and Pop the stack. Repeat this
step as long as stack is not empty.
Return the Postfix string.

Example :
Let us see how the above algorithm will be imlemented using an example.
Infix String : a+b*c-d
Initially the Stack is empty and our Postfix string has no characters. Now, the first character scanned is 'a'.
'a' is added to the Postfix string. The next character scanned is '+'. It being an operator, it is pushed to the
stack.

Postfix String
Stack

Dept of Information Science & Engineering, SCE

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

Next character scanned is 'b' which will be placed in the Postfix string. Next character is '*' which is an
operator. Now, the top element of the stack is '+' which has lower precedence than '*', so '*' will be
pushed to the stack.

Postfix String
Stack
The next character is 'c' which is placed in the Postfix string. Next character scanned is '-'. The topmost
character in the stack is '*' which has a higher precedence than '-'. Thus '*' will be popped out from the
stack and added to the Postfix string. Even now the stack is not empty. Now the topmost element of the
stack is '+' which has equal priority to '-'. So pop the '+' from the stack and add it to the Postfix string. The
'-' will be pushed to the stack.

Postfix String
Stack
Next character is 'd' which is added to Postfix string. Now all characters have been scanned so we must
pop the remaining elements from the stack and add it to the Postfix string. At this stage we have only a '-'
in the stack. It is popped out and added to the Postfix string. So, after all characters are scanned, this is
how the stack and Postfix string will be :

Postfix String
Stack
End result :

Infix String : a+b*c-d


Postfix String : abc*+d-

Program:
#include<conio.h>
#include<stdio.h>
#include<string.h>

Dept of Information Science & Engineering, SCE

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


int in_prec(char);
int stack_prec(char);
void convert(char *,char *);
void main()
{
char in[30],post[30];
clrscr();
printf("Enter a valid infix expression\n");
scanf("%s",in);
convert(in,post);
printf("Postfix expression is %s",post);
getch();
}
int in_prec(char sym)
{
switch(sym)
{
case '+':
case '-': return 1;
case '*':
case '/': return 3;
case '$':
case '^': return 6;
case '(': return 9;
case ')': return 0;
default: return 7;
}
}
int stack_prec(char sym)
{
switch(sym)
{
case '+':
case '-': return 2;
case '*':
case '/': return 4;
case '$':
case '^': return 5;
case '(': return 0;
case '#': return -1;

Dept of Information Science & Engineering, SCE

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


default : return 8;
}
}
void convert(char *in,char *post)
{
char s[30],sym;
int top=-1,i,j=0;
s[++top]='#';
for(i=0;in[i]!='\0';i++)
{
sym=in[i];
while(stack_prec(s[top])>in_prec(sym))
{
post[j++]=s[top--];
}
if(stack_prec(s[top])!=in_prec(sym))
s[++top]=sym;
else
top--;
}
while(s[top]!='#')
post[j++]=s[top--];
post[j]='\0';
}

Sample Output
Enter a valid infix expression
a+b/c
Postfix expression is abc/+

Dept of Information Science & Engineering, SCE

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


3. Design, develop, and execute a program in C to evaluate a valid postfix expression using stack.
Assume that the postfix expression is read as a single line consisting of non-negative single digit
operands and binary arithmetic operators. The arithmetic operators are + (add), - (subtract), *
(multiply) and / (divide).

Description:
Infix Expression :
Any expression in the standard form like "2*3-4/5" is an Infix(Inorder) expression.
Postfix Expression : The Postfix(Postorder) form of the above expression is "23*45/-".
Postfix Evaluation :
The algorithm to evaluate the postfix expression is as follows :

Scan the Postfix string from left to right.


Initialise an empty stack.
If the scannned character is an operand, add it to the stack. If the scanned character is an operator,
there will be atleast 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 :
Let us see how the above algorithm will be imlemented using an example.
Postfix String : 123*+4Initially 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.

Expression
Stack
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.

Dept of Information Science & Engineering, SCE

10

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

Expression
Stack
The value of the expression(2*3) that has been evaluated(6) is pushed into the stack.

Expression
Stack
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.

Expression
Stack
The value of the expression(1+6) that has been evaluated(7) is pushed into the stack.

Expression
Stack
Next character scanned is "4", which is added to the stack.

Expression
Stack

Dept of Information Science & Engineering, SCE

11

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

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.

Expression
Stack
The value of the expression(7-4) that has been evaluated(3) is pushed into the stack.

Expression
Stack
Now, since all the characters are scanned, the remaining element in the stack (there will be only one
element in the stack) will be returned.
End result :

Postfix String : 123*+4Result : 3

Program:
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
int s[20],top=-1;
int evaluate(char *);
void push(int);
int pop();
void main()
{
int res;
char post[30];
Dept of Information Science & Engineering, SCE

12

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


clrscr();
printf("Enter a valid postfix expression\n");
scanf("%s",post);
res=evaluate(post);
printf("Result of expression is %d",res);
getch();
}
int evaluate(char *post)
{
int i,op1,op2,res,x;
char sym;
for(i=0;post[i]!='\0';i++)
{
sym=post[i];
if(isalpha(sym))
{
printf("Enter value for %c:",sym);
scanf("%d",&x);
push(x);
}
else if(isdigit(sym))
push(sym-'0');
else
{
op2=pop();
op1=pop();
switch(sym)
{
case '+':res=op1+op2;
break;
case '-':res=op1-op2;
break;
case '*':res=op1*op2;
break;
case '/':res=op1/op2;

Dept of Information Science & Engineering, SCE

13

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


break;
case '^':res=pow(op1,op2);
break;
default:printf("Invalid operator in the expression is %c\n",sym);
getch();
exit(0);
}
push(res);
}
}
return(pop());
}

void push(int item)


{
top++;
s[top]=item;
}
int pop()
{
return(s[top--]);
}

Sample Output
Case 1 :
Enter a valid postfix expression
63/
Result of expression is 2
Case 2 :
Enter a valid postfix expression
ab+
Enter value for a:10
Enter value for b:5
Result of expression is 15

Dept of Information Science & Engineering, SCE

14

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


4. Design, develop, and execute a program in C to simulate the working of a queue of integers using
an array. Provide the following operations: a. Insert b. Delete c. Display
Description:
Queue :-A queue is a linear list of data elements in which insertion of elements can be done at one end
which is known as front deletion of an element can be done at one end known as rear. Queue follows
FIFO (First in first out) mechanism. The operations that can be performed on a queue are:

Insertion:- Add an element in the front end of a queue.


Deletion:- Deleting an element from the rear end of a queue.

Front(deletion)

rear end(insertion)

Program:
#include<stdio.h>
#include<conio.h>
#define QSIZE 3
#include<stdlib.h>
int choice,item,f,r,q[10];
void insert_rear()
{
if(r==QSIZE-1)
{
printf("over flow\n");
return;
}
printf("Enter the elements to be inserted:\n");
scanf("%d",&item);
q[++r]=item;
}
void delete_front()
{
if(f>r)
{
printf("q is empty\n");
return;
}
printf("The elements deleted is:%d",q[f++]);
}

Dept of Information Science & Engineering, SCE

15

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

void display()
{
int i;
if(f>r)
{
printf("Q is empty\n");
return;
}
printf("The contents of queue:\n");
for(i=f;i<=r;i++)
{
printf("%d\n",q[i]);
}
}
void main()
{
f=0;r=-1;
clrscr();
for(; ;)
{
printf("\n1.Insert\n2.Delete\n3.Display\n4.Exit");
printf("\n enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:insert_rear();
break;
case 2:delete_front();
break;
case 3:display();
break;
default :exit(0);
}
}
}
Sample Output
1.Insert
2.Delete
3.Display
4.Exit
enter your choice:2
Dept of Information Science & Engineering, SCE

16

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


q is empty
1.Insert
2.Delete
3.Display
4.Exit
enter your choice:3
Q is empty

1.Insert
2.Delete
3.Display
4.Exit
enter your choice:1
Enter the elements to be inserted:
63
1.Insert
2.Delete
3.Display
4.Exit
enter your choice:1
Enter the elements to be inserted:
20
1.Insert
2.Delete
3.Display
4.Exit
enter your choice:1
over flow
1.Insert
2.Delete
3.Display
4.Exit
enter your choice:2
The elements deleted is:63
1.Insert
2.Delete
3.Display
4.Exit
enter your choice:3
The contents of queue:
20
1.Insert
2.Delete
3.Display
4.Exit
enter your choice:4
Dept of Information Science & Engineering, SCE

17

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


5. Design, develop, and execute a program in C++ based on the following requirements: An
EMPLOYEE class is to contain the following data members and member functions:
Data members: Employee_Number (an integer), Employee_Name (a string of characters),
Basic_Salary (an integer) , All_Allowances (an integer), IT (an integer), Net_Salary (an integer).
Member functions: to read the data of an employee, to calculate Net_Salary and to print the values
of all the data members. (All_Allowances = 123% of Basic; Income Tax (IT) = 30% of the gross
salary
(= basic_Salary _ All_Allowance); Net_Salary = Basic_Salary +All_Allowances IT)

Description:
Object: Objects are the run time entities in an object oriented system.
Class:A class is an expanded concept of a data structure. The object of same data structure and beheviour
are grouped in to class. Instead of holding only data, it can hold both data members and member
functions.
Once the class has been defined we can create any number of objects belonging to that class.
Example: Mango, Orange, Apple are the members of class fruit. The syntax used to create object is
Fruit mango;
The above statement will create an object mango belonging to the class fruit.
In this program a Class EMPLOYEE is created with the above mentioned data members and member
functions. Object is an instance of class. Required number of objects are created to the EMPLOYEE
class.
Program:

#include<iostream.h>
#include<conio.h>
class employee
{
int emp_no;
char emp_name[20];
float basic,allowances,gross,net,it;
public:
void read();
void calculate();
void display();
};

Dept of Information Science & Engineering, SCE

18

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

void employee::read()
{
cout<<"Enter employee number"<<endl;
cin>>emp_no;
cout<<"Enter employee name"<<endl;
cin>>emp_name;
cout<<"Enter employee salary"<<endl;
cin>>basic;
}
void employee::calculate()
{
allowances=0.123*basic;
gross=basic+allowances;
it=0.3*gross;
net=gross-it;
}
void employee::display()
{
cout<<"\n Employee number is:"<<emp_no<<endl;
cout<<"\n Employee name is:"<<emp_name<<endl;
cout<<"\n basic salary is:"<<basic<<endl;
cout<<"\n gross salary is:"<<gross<<endl;
cout<<"\n net salary is:"<<net<<endl;
}
void main()
{
int n,i;
clrscr();
employee emp[20];
cout<<"enter number of employee:\n"<<endl;
cin>>n;
for(i=0;i<n;i++)
{
cout<<"enter employee details:"<<endl;
emp[i].read();
emp[i].calculate();
}

Dept of Information Science & Engineering, SCE

19

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

cout<<"\n Employee details are:"<<endl;


for(i=0;i<n;i++)
{
emp[i].display();
}
getch();
}

Sample Output
enter number of employee
3
enter employee details:
Enter employee number
10
sanjana
Enter employee salary
6000
enter employee details:
Enter employee number
20
Enter employee name
swathi
Enter employee salary
7000
enter employee details:
Enter employee number
101
Enter employee name
roopa
Enter employee salary
5000

Employee details are:


Employee number is:10
Dept of Information Science & Engineering, SCE

20

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

Employee name is:sanjana


basic salary is:6000
gross salary is:6738
net salary is:4716.600098
Employee number is:20
Employee name is:swathi
basic salary is:7000
gross salary is:7861
net salary is:5502.700195
Employee number is:101
Employee name is:roopa
basic salary is:5000
gross salary is:5615
net salary is:3930.5

Dept of Information Science & Engineering, SCE

21

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


6. Design, develop, and execute a program in C++ to create a class called STRING and implement
the following operations. Display the results after every operation by overloading the operator <<.
i. STRING s1 = VTU
ii. STRING s2 = BELGAUM
iii. STIRNG s3 = s1 + s2; (Use copy constructor)
Description:
Constructor: A constructor is a special function that is a member of the class and has the same name as
class name which is used to perform automatic initialization of the variables.
C++ runtime system make sure that the constructor of the class is the first member function to be
executed when an object of the class is created.
Contructor is executed everytime the object is created.
Example: class classname
{
....
Public: classname( ); //constructor function
}
classname:: classname( )
{
//constructor body
}
Copy Constructor: A Copy constructor is used to declare and initialize an object from another objects.

Program:
#include<iostream.h>
#include<conio.h>
#include<string.h>
class string
{
char name[20];
public:string()
{
name[20]='\0';
}
string(char s[])
{
Dept of Information Science & Engineering, SCE

22

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


strcpy(name, s);
}
string(string &s)
{
strcpy(name, s.name);
}
friend string operator+(string s1, string s2);
friend ostream &operator<<(ostream &out, string &s);
};
ostream &operator<<(ostream &out, string &s)
{
out<<"\t"<<s.name<<endl;
return (out);
}
string operator+(string s1, string s2)
{
string temp(s1);
strcat(temp.name, s2.name);
return(temp);
}
void main()
{
clrscr();
string s1("VTU");
string s2("BELGAUM");
string s3=s1+s2;
cout<<"\nfirst string="<<s1<<"\nsecond string="<<s2<<"\nconcatenated third string="<<s3;
getch();
}

Sample Output
first string= VTU
second string= BELGAUM
concatenated third string=

VTUBELGAUM

Dept of Information Science & Engineering, SCE

23

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


7. Design, develop, and execute a program in C++ to create a class called STACK using an array of
integers and to implement the following operations by overloading the operators + and - :
i. s1=s1 + element; where s1 is an object of the class STACK and element is an integer to be pushed
on to top of the stack.
ii. s1=s1- ; where s1 is an object of the class STACK and operator pops off the top element.
Handle the STACK Empty and STACK Full conditions. Also display the contents of the stack after
each operation, by overloading the operator <<.
Description:
Stack :- A stack is a linear data structure consisting a list of elements in which elements can be inserted
or deleted at one end which is known as TOP of the stack. Stacks follows LIFO (last in first out)
mechanism. The operations that can be performed on a stack are:

Push: Adding an element to the Top of stack.


Pop: Deleting an element from the Top of the stack.

Top

Program:
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
#define max 5
class stack
{
int a[max],top;
public: stack()
{
top=-1;
}
stack operator+(int);
stack operator--();
friend void operator<<(ostream&,stack&);
};

Dept of Information Science & Engineering, SCE

24

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

stack stack::operator+(int item)


{
if(top==max-1)
cout<<"\nstack full";
else
a[++top]=item;
return*this;
}
stack stack::operator--()
{
if(top==-1)
cout<<"\nstack empty";
else
cout<<"\nthe deleted element="<<a[top--];
return*this;
}
void operator<<(ostream&out,stack&object)
{
if(object.top==-1)
cout<<"\nstack empty";
else
cout<<"contents of stack are"<<endl;
for(int i=0;i<=object.top;i++)
cout<<object.a[i]<<endl;
}
void main()
{
stack object;
clrscr();
for(;;)
{
cout<<"\nenter the choice of operation:";
cout<<"\n1.push\n2.pop\n3.display\n4.exit\n";
int choice;
cin>>choice;
switch(choice)
{
case 1:cout<<"\nenter the elements:";

Dept of Information Science & Engineering, SCE

25

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


int item;
cin>>item;
object=object+item;
break;
case 2:object=--object;
break;
case 3:cout<<object;
break;
case 4:exit(0);
}
}
getch();
}

Sample Output
enter the choice of operation:
1.push
2.pop
3.display
4.exit
2
stack empty
1.push
2.pop
3.display
4.exit
3
stack empty
enter the choice of operation:
1.push
2.pop
3.display
4.exit
1
enter the elements:34
enter the choice of operation:
1.push
2.pop
3.display
4.exit
1
enter the elements:67

Dept of Information Science & Engineering, SCE

26

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


enter the choice of operation:
1.push
2.pop
3.display
4.exit
1
enter the elements:6
enter the choice of operation:
1.push
2.pop
3.display
4.exit
3
contents of stack are
34
67
6
enter the choice of operation:
1.push
2.pop
3.display
4.exit
4

Dept of Information Science & Engineering, SCE

27

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


8. Design, develop, and execute a program in C++ to create a class called LIST (linked list) with
member functions to insert an element at the front of the list as well as to delete an element from
the front of the list. Demonstrate all the functions after creating a list object.
Description:
Linked List:- A linked list is a linear collection of data elements. A linked list consists of two important
parts, first part named as info contains the data and the other part named as link consists of a link to the
next element. The info part gives the information while the link part gives the address of the next node.
The operations performed on a linked list are:

Traversing all the elements in the linked list.


Searching for an element in the linked list.
Insertion of an element.
Deletion of an element.

Linked list is a dynamic data structure whose length can be increased or decreased at run time.
Types of linked lists are : 1. Singly linked list
2. Doubly linked list
In this program we learn SLL. Drawback of SLL is that it can be traversed in only one direction(forward).
Bidirectional or backward traversal is not possible.
Program:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int info;
node*link;
};
typedef struct node* NODE;
class list
{
NODE first;
public:
list()
{
first=NULL;
}
void insert(int);
Dept of Information Science & Engineering, SCE

28

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


void delet();
void display();
};
void list::insert(int item)
{
NODE temp=new node;
temp->info=item;
temp->link=first;
first=temp;
}
void list::delet()
{
if(first==NULL)
{
cout<<"the list is empty"<<endl;
return;
}
NODE temp=first;
first=first->link;
cout<<"the deleted element is:"<<temp->info<<endl;
}
void list::display()
{
if(first==NULL)
{
cout<<"list is empty"<<endl;
return;
}
NODE temp=first;
cout<<"\n contents of list are:";
while(temp!=NULL)
{
cout<<temp->info<<"->";
temp=temp->link;
}
}
void main()
{
list object;
clrscr();

Dept of Information Science & Engineering, SCE

29

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

for(;;)
{
cout<<"\nenter the choice"<<endl;
cout<<"1.insert\n2.delete\n3.display\n4.exit"<<endl;
int choice;
cin>>choice;
switch(choice)
{
case 1:cout<<"enter an element:";
int item;
cin>>item;
object.insert(item);
break;
chase 2:object.delet();
break;
case 3:object.display();
break;
case 4:exit(0);
}
}
getch();
}

Sample Output
enter the choice
1.insert
2.delete
3.display
4.exit
2
the list is empty
enter the choice
1.insert
2.delete
3.display
4.exit
1
enter an element:23

Dept of Information Science & Engineering, SCE

30

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


enter the choice
1.insert
2.delete
3.display
4.exit
1
enter an element:2
enter the choice
1.insert
2.delete
3.display
4.exit
3
contents of list are:2->23->
enter the choice
1.insert
2.delete
3.display
4.exit
2
the deleted element is:2
enter the choice
1.insert
2.delete
3.display
4.exit
3
contents of list are:23->
enter the choice
1.insert
2.delete
3.display
4.exit
4

Dept of Information Science & Engineering, SCE

31

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


9. Design, develop, and execute a program in C to read a sparse matrix of integer values and to
search the sparse matrix for an element specified by the user. Print the result of the search
appropriately. Use the triple <row, column, value> to represent an element in the sparse matrix.

Description:
A sparse matrix can be vaguely defined as a matrix with few nonzeros.
Consider a matrix in which most of the entries are zeros. In this case large amount of memory is wasted to
explicitly store all those zeros. when performing operations on the matrices such as addition, subtraction
and multiplication (especially), a large number of the operations have two operands of zero (0) which
results in a large amount of wasted time.
If a matrix is sparse time and space, we can store the elements that are non-zero only and implicitly
assuming any element not stored is 0. This greatly reduces the number of times to be stored and the
number of operations that must be performed for addition, subtraction and multiplication etc.. So instead
of using 2D, we can use some other data structures to store elements of matrices and the data structure
used in this program is Coordinate list(COO)
COO stores a list of (row, column, value) tuples. Ideally, the entries are sorted (by row index, then
column index) to improve random access times..
Description:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX_TERMS 10
struct term
{
int row,col,val;
}
a[MAX_TERMS];
void main()
{
int i,item;
clrscr();
printf("enter total number of rows,columns,&values\n");
scanf("%d%d%d", &a[0].row,&a[0].col,&a[0].val);
printf("enter the values along with row &coloumn");
for(i=1;i<=a[0].val;i++)
scanf("%d%d%d", &a[i].row,&a[i].col,&a[i].val);
Dept of Information Science & Engineering, SCE

32

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

printf("enter the element to be searched");


scanf("%d", &item);
for(i=1;i<=a[0].val;i++)
{
if(item==a[i].val)
{
printf("element found at %d row,%d col\n",a[i].row,a[i].col);
getch();
exit(0);
}
}
printf("search is unsuccessful\n");
getch();
}

Sample Output
enter total number of rows,columns,&values
7
3
5
enter the values along with row &coloumn
124
231
336
512
7 2 10
enter the element to be searched 6
element found at 3 row,3 col

Dept of Information Science & Engineering, SCE

33

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


10. Design, develop, and execute a program in C to create a max heap of integers by accepting one
element at a time and by inserting it immediately in to the heap. Use the array representation for
the heap. Display the array at the end of insertion phase.
Description:
A heap or max heap is a binary tree that satisifies the following properties:
1. it is complete
2. the data item stored in each node is greater than or equal to the data items stored in its children
(this is known as the heap-order property)
A min heap is a binary tree that satisifies the following properties:
1. it is complete
2. the data item stored in each node is less than the data items stored in its children
It's easier to "see" the heap properties when it's drawn as a tree.

Basic Calculations
Assuming that values are stored starting at subscript 1, then

Root of the heap is located at [1]


Left child is located at [2 * parent's position]
Right child is located at [2 * parent's position + 1]
Parent is located at either child's position / 2
Next free location is [number of elements + 1]

Dept of Information Science & Engineering, SCE

34

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

Heapifying a complete binary tree


Starting with the last node that is not a leaf node, compare it with its left and right children. Interchange
the node with the larger of its two children. Continue this process with the node until it becomes a leaf
node or until the heap property is restored. This is known as the percolate down process.
Move to the preceding node that is not a leaf and repeat the percolate down process. Continue this
process until the root is reached.

There are two basic operations that can be performed on a heap:


1. Inserting an item into a heap
2. Finding and removing the maximum item from the heap

Inserting into a max heap


Step 1: Insert the node in the first available level order position.
Step 2: Compare the newly inserted node with its parent. If the newly inserted node is larger, swap it with
its parent.
Step 3: Continue step 2 until the heap order property is restored.
Steps 2 and 3 are known as the percolate up process.

Dept of Information Science & Engineering, SCE

35

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

Deleting from a max heap


Step 1: Find the maximum node.
Step 2: Replace the maximum node with the last leaf node in level order.
Step 3: Compare the replacement against its children. If one of the children is larger, swap the
replacement with the largest child.
Step 4: Repeat step 3 until the heap order property is restored.
Does this process seem familiar?

Dept of Information Science & Engineering, SCE

36

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


Program:
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
#define max_size 10
int insert_heap(int ,int* ,int );
void display(int*,int );
void main()
{
int a[max_size];
int n=0;
int choice,item;
clrscr();
for(;;)
{
printf("1.insert 2.display\n");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("enter the item to be inserted:\n");
scanf("%d",&item);
n=insert_heap(item,a,n);
break;
case 2:display(a,n);
break;
default:exit(0);
}
}
}
int insert_heap(int item,int a[],int n)
{
int c,p;
if(n==max_size)
{
printf("heap is full\n");
return n;
}
c=n;
p=(c-1)/2;

Dept of Information Science & Engineering, SCE

37

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


while(c!=0 && item>a[p])
{
a[c]=a[p];
c=p;
p=(c-1)/2;
}
a[c]=item;
return(n+1);
}
void display(int a[],int n)
{
int i;
if(n==0)
{
printf("heap is empty");
return;
}
printf("the max heap contents are:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\n");
getch();
return;
}

Sample Output
1.insert 2.display
2
heap is empty
1.insert 2.display
1
enter the item to be inserted:
2
1.insert 2.display
1
enter the item to be inserted:
4
1.insert 2.display
1
enter the item to be inserted:
67
Dept of Information Science & Engineering, SCE

38

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


1.insert 2.display
2
the max heap contents are:
67
2
4
1.insert 2.display
1
enter the item to be inserted:
56
1.insert 2.display
1
enter the item to be inserted:
7
1.insert 2.display
1
enter the item to be inserted:
88
1.insert 2.display
2
the max heap contents are:
88
56
67 2
7
4
1.insert 2.display
3

Dept of Information Science & Engineering, SCE

39

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


11. Design, develop, and execute a program in C to implement a doubly linked list where each node
consists of integers. The program should support the following operations:
i. Create a doubly linked list by adding each node at the front.
ii. Insert a new node to the left of the node whose key value is read as an input.
iii. Delete the node of a given data if it is found, otherwise display appropriate message.
iv. Display the contents of the list.
(Note: Only either (a,b and d) or (a, c and d) may be asked in the examination)

Description:

To traverse a list both forwards and backwards efficiently, or given a list element, to determine the
preceding and following elements quickly, then the doubly-linked list comes in handy. A list element
contains the data plus pointers to the next and previous list items as shown in the picture below.

Of course we need a pointer to some link in the doubly-linked list to access list elements. It is convenient
for doubly-linked lists to use a list header, or head, that has the same structure as any other list item and is
actually part of the list data structure. The picture below shows an empty and nonempty doubly-linked
list. By following arrows it is easy to go from the list header to the first and last list element, respectively.

Dept of Information Science & Engineering, SCE

40

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


Insertion and removal of an element in a doubly-linked list is in this implementation rather easy. In the
picture below we illustrate the pointer changes for a removal of a list item (old pointers have been drawn
solid and new pointers are dashed arrows). We first locate the previous list item using the previous field.
We make the next field of this list item point to the item following the one in cursor position pos. Then
we make the previous field of this following item point to the item preceding the one in the cursor
position pos. The list item pointed to by the cursor becomes useless and should be automatically garbage
collected.

Program:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<malloc.h>
struct node
{
int info;
struct node*llink;
struct node*rlink;
};
typedef struct node*NODE;
NODE first=NULL;
void ins_front(int item);
void ins_left(int key, int item);
void del(int key);
void display();
void main()
{

Dept of Information Science & Engineering, SCE

41

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


int choice,item,key;
clrscr();
for(;;)
{
printf("1.insert front\n2.insert left\n3.del key\n4.display\n5.exit\n");
printf("Enter your choice");
scanf("%d", &choice);
switch(choice)
{
case 1:printf("enter the item to be inserted\n");
scanf("%d", &item);
ins_front(item);
break;
case 2:printf("left of which node?:\n");
scanf("%d",&key);
printf("enter the item to be inserted\n");
scanf("%d",&item);
ins_left(key, item);
break;
case 3:printf("enter the item to be deleted");
scanf("%d",&key);
del(key);
case 4: display();
break;
default: exit(0);
}
}
}
void ins_front(int item)
{
NODE nn=(NODE)malloc(sizeof(struct node));
nn->info=item;
nn->rlink=nn->llink=NULL;
if(first==NULL)
{
first=nn;
return;
}
nn->rlink=first;
first->llink=nn;
first=nn;
}

Dept of Information Science & Engineering, SCE

42

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

void display()
{
NODE temp=first;
if(first==NULL)
{
printf("list is empty\n");
return;
}
if(first->llink==NULL&&first->rlink==NULL)
{
printf("The element present is %d", first->info);
return;
}
printf("elements of the list are:\n");
while (temp!=NULL)
{
printf("%d->", temp->info);
temp=temp->rlink;
}
}
void ins_left(int key, int item)
{
NODE temp, prev;
NODE nn=(NODE)malloc(sizeof(struct node));
nn->info=item;
nn->rlink=nn->llink=NULL;
if(first==NULL)
{
printf("list is empty\n");
return;
}
temp=first;
while(temp!=NULL)
{
if(temp->info==key)

Dept of Information Science & Engineering, SCE

43

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


{
prev=temp->llink;
nn->rlink=temp;
prev->rlink=nn;
nn->llink=prev;
temp->llink=nn;
printf("new node is successfully inserted\n");
return;
}
temp=temp->rlink;
}
printf("given number is not there in the list\n");
}
void del(int key)
{
NODE temp, prev, next;
if(first==NULL)
{
printf("list is empty\n");
return;
}
temp=first;
if(first->info==key)
{
first=first->rlink;
first->llink=NULL;
printf("deleted node is %d", temp->info);
free(temp);
return;
}
while(temp!=NULL)
{
if(temp->info==key)
{
prev=temp->llink;
next=temp->rlink;
prev->rlink=temp->rlink;
next->llink=prev;
printf("deleted node is %d", temp->info);
free(temp);
return;
}

Dept of Information Science & Engineering, SCE

44

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


temp=temp->rlink;
}
printf("given number is not there in the list\n");
}

Sample Output
1.insert front
2.insert left
3.del key
4.display
5.exit
Enter your choice 1
enter the item to be inserted
23
1.insert front
2.insert left
3.del key
4.display
5.exit
Enter your choice 1
enter the item to be inserted
27
1.insert front
2.insert left
3.del key
4.display
5.exit
Enter your choice 4
elements of the list are:
27->23->
1.insert front
2.insert left
3.del key
4.display
5.exit
Enter your choice 2
left of which node?:
23
enter the item to be inserted
5
new node is successfully inserted
Dept of Information Science & Engineering, SCE

45

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

1.insert front
2.insert left
3.del key
4.display
5.exit
Enter your choice4
elements of the list are:
27->5->23->
1.insert front
2.insert left
3.del key
4.display
5.exit
Enter your choice 3
enter the item to be deleted 23
deleted node is 23elements of the list are:
27->5->

1.insert front
2.insert left
3.del key
4.display
5.exit
Enter your choice 5

Dept of Information Science & Engineering, SCE

46

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


12. Design, develop, and execute a program in C++ to create a class called DATE with methods to
accept two valid dates in the form dd/mm/yy and to implement the following operations by
overloading the operators + and -. After every operation the results are to be displayed by
overloading the operator <<.
i. no_of_days = d1 d2; where d1 and d2 are DATE objects, d1 >=d2 and no_of_days is an integer.
ii. d2 = d1 + no_of_days; where d1 is a DATE object and no_of_days is an integer.
Description:
Polymorphism is achieved in C++ using opeartor overloading. It is an opration that can exhibit different
beheviour in different instances
Operator overloading permits user-defined operator implementations to be specified for operations where
one or both of the operands are of a user-defined class. it is possible to overload most of C++ operators by
defining what they mean relative to the specific class
Example: if + operator is implemented with 2 numbers, the operation will generate a sum of 2 numbers.
Simlarly the same operator can be implemented to produce third string by concatenation of
two strings.So, + oprator is behaving differently in different instances
Program:
#include<iostream.h>
#include<conio.h>
class date
{
int dd,mm,yy;
int a[13];
long double noofdays;
void getno();
public:
date()
{
a[1]=a[3]=a[5]=a[7]=a[8]=a[10]=a[12]=31;
a[4]=a[6]=a[9]=a[11]=30;
a[2]=28;
dd=mm=yy=1;
}
void getdate();
friend ostream &operator<<(ostream &,date &);
long double operator-(date &);
Dept of Information Science & Engineering, SCE

47

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


date operator +(long double);
};
void date::getdate()
{
cout<<"enter date:";
cout<<"\ndate is:\n";
cin>>dd;
cout<<"month is:\n";
cin>>mm;
cout<<"year is:\n";
cin>>yy;
while((yy%4!=0 && dd>a[mm])||(yy%4==0 && mm==2 && dd>29)||(dd<=0) ||
(dd>31)||(mm<=0)||(mm>12))
{
cout<<"invalid entry\n";
getdate();
}
getno();
}
void date::getno()
{
int m=1;
noofdays=(long double)(yy-1)*365;
while(m!=mm)
{
noofdays=noofdays+a[m];
if(yy%4==0 && m==2)
noofdays++;
m++;
}
noofdays+=dd;
}
ostream &operator<<(ostream &out,date &d1)
{
out<<d1.dd<<"/"<<d1.mm<<"/"<<d1.yy<<"\n";
return out;
}
long double date::operator-(date &b)

Dept of Information Science & Engineering, SCE

48

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


{
return (noofdays-b.noofdays);
}
date date::operator+(long double b)
{
for(int i=1;i<=b;i++)
{
dd++;
if(dd>a[mm])
{
mm++;
dd=1;
}
if(mm>12)
{
yy++;
mm=1;
}
if(yy%4==0)
a[2]=29;
}
return(*this);
}
void main()
{
date d1,d2,d3;
clrscr();
d1.getdate();
cout<<"\nd1="<<d1;
d2.getdate();
cout<<"\nd2="<<d2;
long double s;
s=d1-d2;
cout<<"difference between two dates is:"<<s;
cout<<"\nenter no of days to be added to:"<<d1<<":";
cin>>s;
d3=d1+s;
cout<<"new date is:"<<d3;
getch();
}

Dept of Information Science & Engineering, SCE

49

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


Sample Output
enter date:
date is:
23
month is:
3
year is:
2002
d1=23/3/2002
enter date:
date is:
3
month is:
6
year is:
2002
d2=3/6/2002
difference between two dates is:-72
enter no of days to be added to:23/3/2002
:45
new date is:7/5/2002

Dept of Information Science & Engineering, SCE

50

DATA STRUCTURES WITH C/C++ LAB


LABORATORY MANUAL (10CSL37)
13. Design, develop, and execute a program in C++ to create a class called OCTAL, which has the
characteristics of an octal number. Implement the following operations by writing an appropriate
constructor and an overloaded operator +.
i. OCTAL h = x ; where
re x is an integer
ii. int y = h + k ; where h is an OCTAL object and k is an integer.
Display the OCTAL result by overloading the operator <<. Also display the values of h and y.

Description:
The octal numeral system, or oct for short, is the base-8
8 number system, and uses the digits 0 to 7. Octal
numerals can be made from binary numerals by grouping consecutive binary digits into groups of three
(starting from the right). For example, the binary representation for decimal 74 is 1001010,
1001010 which can be
grouped into (00)1 001 010 so the octal representation is 112. In the decimal system each decimal place
is a power of ten. For example:

In the octal system each place is a power of eight. For example:

By performing the calculation abov


abovee in the familiar decimal system we see why 112 in octal is equal to
64+8+2 = 74 in decimal.
Program:
#include<conio.h>
#include<iostream.h>
#include<stdlib.h>
#include<math.h>
class octal
{
int oct[15],count;
public:
octal(int x);
int operator +(int k);
friend ostream &operator<<(ostream &,octal &);
};
octal::octal(int x)
{
int i=0,rem=0,a[15];
while(x!=0)
Dept of Information Science & Engineering
ngineering, SCE

51

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


{
rem=x%8;
x=x/8;
a[i++]=rem;
}
count=i;
int n=count-1;
for(i=0;i<count;i++)
{
oct[i]=a[n];
n--;
}
}
int octal::operator +(int k)
{
int x=0,i;
int j=count-1;
for(i=0;i<count;i++)
{
x=x+oct[j]*pow(8,i);
j--;
}
return(x+k);
}
ostream &operator <<(ostream &print,octal &o)
{
for(int i=0;i<o.count;i++)
print<<o.oct[i];
return(print);
}
void main()
{
int x,k,y=0;
clrscr();
cout<<"Enter integer value in decimal:";
cin>>x;
octal h=x;
cout<<"The corresponding octal value for("<<x<<") is:"<<h;
cout<<"\n\nEnter the value added to octal value:";
cin>>k;
y=h+k;

Dept of Information Science & Engineering, SCE

52

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


cout<<"\n"<<h<<"(octal)+"<<k<<"(decimal)="<<y<<"(decimal)";
getch();
}

Sample Output
Enter integer value in decimal:45
The corresponding octal value for(45) is:55
Enter the value added to octal value:9
55(octal)+9(decimal)=54(decimal)

Dept of Information Science & Engineering, SCE

53

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


14. Design, develop, and execute a program in C++ to create a class called BIN_TREE that
represents a Binary Tree, with member functions to perform inorder, preorder and postorder
traversals. Create a BIN_TREE object and demonstrate the traversals.
Description:

A binary tree is made of nodes, where each node


contains a "left" reference, a "right" reference, and a
data element. The topmost node in the tree is called the
root.
Every node (excluding a root) in a tree is connected by a
directed edge from exactly one other node. This node is
called a parent. On the other hand, each node can be
connected to arbitrary number of nodes, called children.
Nodes with no children are called leaves, or external
nodes. Nodes which are not leaves are called internal
nodes. Nodes with the same parent are called siblings.

More tree terminology:

The depth of a node is the number of edges from the root to the node.
The height of a node is the number of edges from the node to the deepest leaf.
The height of a tree is a height of the root.
A full binary tree.is a binary tree in which each node has exactly zero or two children.
A complete binary tree is a binary tree, which is completely filled, with the possible exception of
the bottom level, which is filled from left to right.

Dept of Information Science & Engineering, SCE

54

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


A complete binary tree is very special tree, it provides the best possible ratio between the number of
nodes and the height. The height h of a complete binary tree with N nodes is at most O(log N). We can
easily prove this by counting nodes on each level, starting with the root, assuming that each level has the
maximum number of nodes:
n = 1 + 2 + 4 + ... + 2h-1 + 2h = 2h+1 - 1
Solving this with respect to h, we obtain
h = O(log n)
where the big-O notation hides some superfluous details.
Advantages of trees
Trees are so useful and frequently used, because they have some very serious advantages:

Trees reflect structural relationships in the data


Trees are used to represent hierarchies
Trees provide an efficient insertion and searching
Trees are very flexible data, allowing to move subtrees around with minumum effort

Traversals
A traversal is a process that visits all the nodes in the tree. Since a tree is a nonlinear data structure, there
is no unique traversal. We will consider several traversal algorithms with we group in the following two
kinds

depth-first traversal
breadth-first traversal

There are three different types of depth-first traversals, :

PreOrder traversal - visit the parent first and then left and right children;
InOrder traversal - visit the left child, then the parent and the right child;
PostOrder traversal - visit left child, then the right child and then the parent;

There is only one kind of breadth-first traversal--the level order traversal. This traversal visits nodes by
levels from top to bottom and from left to right.

Dept of Information Science & Engineering, SCE

55

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

As an example consider the following tree and its


four traversals:
PreOrder - 8, 5, 9, 7, 1, 12, 2, 4, 11, 3
InOrder - 9, 5, 1, 7, 2, 12, 8, 4, 3, 11
PostOrder - 9, 1, 2, 12, 7, 5, 3, 11, 4, 8
LevelOrder - 8, 5, 4, 9, 7, 11, 1, 12, 3, 2

In the next picture we demonstarte the order of node visitation. Number 1 denote the first node in a
particular traversal and 7 denote the last node.

These common traversals can be represented as a single algorithm by assuming that we visit each node
three times. An Euler tour is a walk around the binary tree where each edge is treated as a wall, which
you cannot cross. In this walk each node will be visited either on the left, or under the below, or on the
right. The Euler tour in which we visit nodes on the left produces a preorder traversal. When we visit
nodes from the below, we get an inorder traversal. And when we visit nodes on the right, we get a
postorder traversal.

Dept of Information Science & Engineering, SCE

56

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


Program:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int info;
struct node *left,*right;
};
typedef node* NODE;
class BINTREE
{
public:
NODE root;
public:
BINTREE()
{
root=NULL;
}
void preorder(NODE root)
{
if(root!=NULL)
{
cout<<root->info<<"\t";
preorder(root->left);
preorder(root->right);
}
}
void postorder(NODE root)
{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
cout<<root->info<<"\t";
}
}
void inorder(NODE root)
{

Dept of Information Science & Engineering, SCE

57

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


if(root!=NULL)
{
inorder(root->left);
cout<<root->info<<"\t";
inorder(root->right);
}
}
void insert()
{
int item,opt=1;
char dir;
NODE temp,prev;
do
{
NODE nn=new (struct node);
cout<<"enter a number"<<endl;
cin>>item;
nn->info=item;
nn->left=nn->right=NULL;
if(root==NULL)
root=nn;
else
{
temp=root; prev=NULL;
while(temp!=NULL)
{
cout<<"enter the direction\tleft/right of "<<temp->info<<":";
cin>>dir;
if(dir=='L' || dir=='l')
{
prev=temp;
temp=temp->left;
}
else if(dir=='R' || dir=='r')
{
prev=temp;
temp=temp->right;
}
else
{
cout<<"invalid direction"<<endl;
break;
}
}

Dept of Information Science & Engineering, SCE

58

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)

if(dir=='L' || dir=='l')
prev->left=nn;
else
prev->right=nn;
cout<<"continue with next node(1/0)\t";
cin>>opt;
}
}while(opt);
}
};
void main()
{
BINTREE bin;
clrscr();
int choice;
for(;;)
{
cout<<"1.insert 2.inorder 3.preorder 4.postorder 5.exit"<<endl;
cout<<"enter choice:";
cin>>choice;
switch(choice)
{
case 1:bin.insert();
break;
case 2:if(bin.root==NULL)
cout<<"Tree is empty"<<endl;
else
{
cout<<"Inorder traversal is:"<<endl;
bin.inorder(bin.root);
cout<<endl;
}
break;
case 3:if(bin.root==NULL)
cout<<"Tree is empty"<<endl;
else
{
cout<<"Preorder traversal is:"<<endl;
bin.preorder(bin.root);
cout<<endl;

Dept of Information Science & Engineering, SCE

59

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


}
break;
case 4:if(bin.root==NULL)
cout<<"Tree is empty"<<endl;
else
{
cout<<"Postorder traversal is:"<<endl;
bin.postorder(bin.root);
cout<<endl;
}
break;
default:exit(0);
}
}
}

Sample Output

1.insert 2.inorder 3.preorder 4.postorder 5.exit


enter choice:1
enter a number
34
enter a number
23
enter the direction left/right of 34:l
continue with next node(1/0) 1
enter a number
23
enter the direction left/right of 34:l
enter the direction left/right of 23:r
continue with next node(1/0) 1
enter a number
5
enter the direction left/right of 34:r
continue with next node(1/0) 1
enter a number
67
enter the direction
enter the direction

left/right of 34:r
left/right of 5:r

Dept of Information Science & Engineering, SCE

60

DATA STRUCTURES WITH C/C++ LABORATORY MANUAL (10CSL37)


continue with next node(1/0) 0
1.insert 2.inorder 3.preorder 4.postorder 5.exit
enter choice:2
Inorder traversal is:
23
23
34 5
67
1.insert 2.inorder 3.preorder 4.postorder 5.exit
enter choice:3
Preorder traversal is:
34
23
23 5
67
1.insert 2.inorder 3.preorder 4.postorder 5.exit
enter choice:4
Postorder traversal is:
23
23
67 5
34
1.insert 2.inorder 3.preorder 4.postorder 5.exit
enter choice:5

Dept of Information Science & Engineering, SCE

61

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy