Download DATA STRUCTURES WITH C/C++ LABORATORY

Document related concepts
Transcript
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
DATA STRUCTURES
Data Structures:
The logical or mathematical model of a particular organization of data is called data
structures. Data structures is the study of logical relationship existing between individual
data elements, the way the data is organized in the memory and the efficient way of storing,
accessing and manipulating the data elements.
Choice of a particular data model depends on two considerations: it must be rich
enough in structure to mirror the actual relationships of the data in the real world. On the
other hand, the structure should be simple enough that one can effectively process the data
when necessary.
Data Structures can be classified as:
Primitive data structures
Non-Primitive data structures.
Primitive data structures are the basic data structures that can be directly
manipulated/operated by machine instructions. Some of these are character, integer, real,
pointers etc.
Non-primitive data structures are derived from primitive data structures, they cannot
be directly manipulated/operated by machine instructions, and these are group of
homogeneous or heterogeneous data items. Some of these are Arrays, stacks, queues, trees,
graphs etc.
Data structures are also classified as
Linear data structures
Non-Linear data structures.
In the Linear data structures processing of data items is possible in linear fashion, i.e., data
can be processed one by one sequentially.
Example of such data structures are:
Array
Linked list
Stacks
Queues
A data structure in which insertion and deletion is not possible in a linear fashion is
called as non linear data structure. i.e., which does not show the relationship of logical
adjacency between the elements is called as non-linear data structure. Such as trees, graphs
and files.
Data structure operations:
The particular data structures that one chooses for a given situation depends largely
on the frequency with which specific operations are performed. The following operations play
major role in the processing of data.
i) Traversing.
ii) Searching.
iii) Inserting.
iv) Deleting.
v) Sorting.
vi) Merging
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
1
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
STACKS:
A stack is an ordered collection of items into which new items may be inserted and
from which items may be deleted at the same end, called the TOP of the stack. A stack is a
non-primitive linear data structure. As all the insertion and deletion are done from the same
end, the first element inserted into the stack is the last element deleted from the stack and
the last element inserted into the stack is the first element to be deleted. Therefore, the
stack is called Last-In First-Out (LIFO) data structure.
QUEUES:
A queue is a non-primitive linear data structure. Where the operation on the queue is
based on First-In-First-Out FIFO process — the first element in the queue will be the first one
out. This is equivalent to the requirement that whenever an element is added, all elements
that were added before have to be removed before the new element can be removed.
For inserting elements into the queue are done from the rear end and deletion is done
from the front end, we use external pointers called as rear and front to keep track of the
status of the queue. During insertion, Queue Overflow condition has to be checked. Likewise
during deletion, Queue Underflow condition is checked.
LINKED LIST:
Disadvantages of static/sequential allocation technique:
1) If an item has to be deleted then all the following items will have to be moved by one
allocation. Wastage of time.
2) Inefficient memory utilization.
3) If no consecutive memory (free) is available, execution is not possible.
Linear Linked Lists
Types of Linked lists:
1) Single Linked lists
2) Circular Single Linked Lists
3) Double Linked Lists
4) Circular Double Linked Lists.
NODE:
Each node consists of two fields. Information (info) field and next address(next) field.
The info field consists of actual information/data/item that has to be stored in a list. The
second field next/link contains the address of the next node. Since next field contains the
address, It is of type pointer.Here the nodes in the list are logically adjacent to each other.
Nodes that are physically adjacent need not be logically adjacent in the list.
The entire linked list is accessed from an external pointer FIRST that points to (contains the
address of) the first node in the list. (By an “external” pointer, we mean, one that is not
included within a node. Rather its value can be accessed directly by referencing a variable).
NODE
INFO
Dept. of CSE, CIT, Gubbi- 572 216
NEXT
PAGE NO.
2
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
The list containing 4 items/data 10, 20, 30 and 40 is shown below.
FIRST
INFO
NEXT
INFO
10
NODE1
NEXT
20
NODE2
INFO
NEXT
TTT
30
NODE3
INFO
NEXT
TT
40
NODE4
The nodes in the list can be accessed using a pointer variable. In the above fig. FIRST
is the pointer having the address of the first node of the list, initially before creating the list,
as list is empty. The FIRST will always be initialized to NULL in the beginning. Once the list is
created, FIRST contains the address of the first node of the list.
As each node is having only one link/next, the list is called single linked list and all the nodes
are linked in one direction.
Each node can be accessed by the pointer pointing (holding the address) to that node,
Say P is pointer to a particular node, then the information field of that node can be accessed
using info(P) and the next field can be accessed using next(P).
The arrows coming out of the next field in the fig. indicates that the address of the
succeeding node is stored in that field.
The link field of last node contains a special value known as NULL which is shown using a
diagonal line pictorially. This NULL pointer is used to signal the end of a list.
The basic operations of linked lists are Insertion, Deletion and Display. A list is a
dynamic data structure. The number of nodes on a list may vary dramatically as elements
are inserted and deleted(removed). The dynamic nature of list may be contrasted with the
static nature of an array, whose size remains constant. When an item has to inserted, we will
have to create a node, which has to be got from the available free memory of the computer
system, So we shall use a mechanism to find an unused node which makes it available to us.
For this purpose we shall use the getnode operation (getnode() function).
The C language provides the built-in functions like malloc(), calloc(), realloc() and
free(), which are stored in alloc.h or stdlib.h header files. To dynamically allocate and release
the memory locations from/to the computer system.
TREES:
Definition: A data structure which is accessed beginning at the root node. Each node is
either a leaf or an internal node. An internal node has one or more child nodes and is called
the parent of its child nodes. All children of the same node aresiblings. Contrary to a physical
tree, the root is usually depicted at the top of the structure, and the leaves are depicted at
the bottom. A tree can also be defined as a connected, acyclic di-graph.
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
3
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Binary tree: A tree with utmost two children for each node.
Complete binary tree: A binary tree in which every level, except possibly the deepest, is
completely filled. At depth n, the height of the tree, all nodes must be as far left as possible.
Binary search tree: A binary tree where every node’s left subtree has keys less than the
node's key, and every right subtree has keys greater than the node's key.
Tree traversal is a technique for processing the nodesof a tree in some order.
The different tree traversal techniques are Pre-order, In-order and Post-order traversal.
In Pre-order traversal, the tree node is visited first and the left subtree is traversed
recursively and later right sub-tree is traversed recursively.
Object Oriented Programming (OOP)
Object-oriented or object oriented programming (OOP) is introduced as a new
programming concept which should help one in developing high quality software.Objectorientation is also introduced as a concept which makes developing of projects easier. Object
oriented programming attempts to solve the problems with only one approach; dividing the
problems in sub-modules and using different objects. Objects of the program interact by
sending messages to each other. The drawing below illustrates this clearly.
Object–oriented programming treats data as a critical element in the program
development and does not allow it to flow freely around the system. It ties data more closely
to the functions that operate on it from accidental modification from outside functions. It
allows decomposition of a problem into a number of entities called objects and than builds
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
4
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
data and function around these objects. The organization of data and functions in oop is
shown in below fig1.
Some striking features of OOP are

Emphasis is on data rather than procedure

Programs are divided into what are known as objects

Data structures are designed such that they characterize the objects

Functions that operate on the data of an object are tied together in the data
structure

Data is hidden and cannot be accessed by external functions.

Objects may communicate with each other through functions

New data and functions can be easily added whenever necessary.

Follows bottom-up approach in program design.
OOP is an approach that provides a way of modularizing programs by creating
partitioned memory for both data and functions that can be used as templates for creating
copies of such modules on demand.
Concepts of Object-Oriented programming
Object-Oriented Programming is the most recent concept among programming
paradigms, where different people interpret the term Object-Oriented differently. Therefore,
it is necessary to understand some of the concepts, which are used in Object-Oriented
Programming.
Classes:
A Class is a way to bind data and its associated functions together. It allows the data
(and functions) to be hidden, if necessary, from external use. When defining a class, we are
creating a new abstract data type that can be treated like any other built-in data type. Figure
shows two different notations used by the OOP analysis to represent a class. Generally, a
class specification has two parts:
Class : ITEM
DataCustomer
Number
Cost
....
METHODS
Get data
Put data
....
(a)
ITEM
Get data
Put data
....
(b)
Figure: Representation of a class
Class declaration, it declares classes used in the program. It is optional.
definition can be used.
Directly class
A Class definition, which describes the component members (both data members and
member functions) of the class, where the member functions describe how the class member
functions are implemented.
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
5
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
The general form of a class declaration:
Class class-name;
Where Class is keyword and Class-name is the name of the class.Class declaration is optional
i.e. without declaring class directly class can be defined .The general form of a class
definition is :
Class class_name
{
private:
variable declarations;
function declaration;
public:
variable declarations;
function declaration;
protected:
variable declarations;
function declaration;
};
For example,
class student
{
private: char name[10];
int n;
public: void read(char,int);
};
Once a class has been defined, one can create any number of objects belonging to that class.
Defining the class doesn't create any object. A class is thus a collection of similar objects.
Object:
Objects are the basic run-time entities in an Object-Oriented system. Objects can be
classified under the following different types. Each object contains data and code to
manipulate the data. When the program is executed, the objects interact by sending the
message to one another. E.g. if "customer" and "account" are the two objects in a program,
then the customer's object may send the message to the amount object requesting for the
bank balance. Each object contains data, and code to manipulate the data. Objects can
interact without having to know details of each other's data or code. Figure shows two
notations that are popularly used in Object-Oriented analysis and design of systems.
Creating Objects:
Once class has been declared object can be created using class-name
Class-name objects;
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
6
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
For ex.
Student s1,s2;
Accessing class members:
The following is the format for calling a member function: Object_name.functionname(actual arguments); For ex, the function call statement S1.read(10,20);
Defining member functions
Member function can be defined in two places

Outside the class definition.

Inside the class definition
Outside the class definition
Member functions that are declared inside a class have to be defined separately outside the
class. The general form of a member function definition is:
return-type class-name:: function name(argument declaration)
{
function body;
}
The label class-name:: tells the compiler that the function function-name belongs to the class
class-name. i.e, the scope of the function is restricted to the class-name specified in the
header line. The symbol :: is the scope resolution operator
For Ex.
void student::read(char;name[10],int roll-no)
{
function body;
}
Inside the class definition
Another method of defining a member function is to replace the function declaration be the
actual function definition inside the class
For Ex.
Class student
{
int no;
char name[10];
public: void read(char n[10] ,int a)
{
function body;
}
};
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
7
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Data abstraction and encapsulation:
Abstraction refers to the act of representing the enclosed features without including the
background details or explanation. The work strictly concentrates upon the solution of this
problem. Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight and cost, and functions to operate on these attributes. They
encapsulate all the essential properties of the objects that are to be created. Since the
classes are the concept of data abstraction, they are known as abstract data type.
Encapsulation:
The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. Data encapsulation is the most striking feature of a class. The data is not
accessible to the outside world. And only those functions, which are wrapped in the class,
can assess it. These functions provide the interface between the object's data and the
program. This restriction on the data from direct access by the program is called data hiding
or information hiding.
One goal of encapsulation is to prevent programmers from using is that if one is not a
member of a class then he cannot get it.
Inheritance:
Inheritance is the process by which objects of one class acquire the properties of
objects of another class. i.e. the mechanism of deriving a new class from the old one is called
inheritance. The old class is referred to as the base class and the new one is called the derived
class. The derived class inherits some or all the traits from the base class.
Inheritance is the mechanism which allows a class A to inherit properties of a class B. We
say A inherits from B. Objects of class A thus have accesses to attributes and methods of
class B without the need to redefine them. The following definition defines two terms with
which we are able to refer to participating classes when they use inheritance.
Defining derived classes:
A derived class is defined by specifying its relationship with the base class in addition
to its own details. The general form of defining a derived class is
Class derived-class-name : visibility –mode base-class-name
{
//members of derived class
};
ACCESS
ACCESSABLE
ACCESSABLE
ACCESSABLE
SPECIFICATION
FROM OWN
FROM DERIVED
FROM OBJECT
CLASS
CLASS
OUTSIDE CLASS
PUBLIC
YES
YES
YES
PROTECTED
YES
YES
NO
PRIVATE
YES
NO
NO
Table: Access Specifies
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
8
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Types of Inheritance:
A class can also inherit properties from more than one class or from more than one level.
The following are the types of inheritances.
Single inheritance: A derived class with only one base class is called single inheritance,
which is as represented in Figure(a).
Multiple inheritances: A derived class with several base classes is called multiple
inheritances as shown in Figure(b).
Multilevel inheritance: The mechanism of deriving a class from another derived class is
known as multilevel inheritance, which is shown in Figure(c).
Hierarchical inheritance: The traits of one class may be inherited by more than one class.
This process is known as hierarchical inheritance shown in Figure (d).
Hybrid inheritance: The combination of multilevel and multiple inheritance is called as
hybrid inheritance and it is shown in Figure(e).
A
A
B
A
B
B
C
(b)
(a)
C
(c)
A
A
B
D
B
C
D
A
(d)
(d)
Figure: Different types of Inheritance
(a) Single inheritance
(b) Multiple inheritance (c) Multilevel inheritance
(d) Hybrid inheritance (e) Hierarchical inheritance
All forms of inheritance are used for writing extensible programs. The direction of arrow
indicates the direction of inheritance.
The following are the advantages of inheritance.

Code reusability: Reusing code saves time and money and increases program
reliability.

The derived class can add data and member function to the class without affecting the
base class behavior. This is called data abstraction.

The protection can be increased in derived classes, but cannot be decreased. This
means a class item declared as protected in a class cannot be made public later in the
derived classes. Making a public item protected or private in a derived class is
allowed.
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
9
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Polymorphism:
Polymorphism means the ability to take more than one form. For example, an operation
may exhibit different behaviors in different instances. The behavior depends upon the type of
data used in the operation.
For Example, consider the operation of addition of two numbers. The operation generates
a sum. If the operands are strings, the operations produce a third string by concatenation.
Compile-Time Polymorphism:
Polymorphism is implemented using the overloaded functions and operations. The
overloaded member functions are selected for invoking by matching arguments. Both type
and number. This information is known to the compiler is able to select the appropriate
functions. The particular call is made at the compile time itself. This is called early binding or
static binding or static linking or compile-time polymorphism.

Defining Function overloading: It means using the same name to perform the variety
of different tasks. Figure shows an example for function overloading.
Shape
Draw ( )
Circle Object
Box Object
Draw (Circle)
Draw (box)
Example:
Triangle
Object
Draw
(Triangl)
Figure: Example functions overloading.
Class addition
{
private:
int a,b;
float c,d;
double m,n;
public:
add(int a, int b);
add(int a, float c, float d)
add(double m, double n);
};
For this example, the present work outputs that function “add” is an overloaded function.
Defining operator overloading:
To define an additional task to an operator, we must specify what it means in relation to the
class to which the operator is applied. This is done with the help of a special function, called
operator function, which describes the task. The general form of operator function is:
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
10
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Return-type class-name :: operator op(arg-list)
{
function body;
}
Where return type is the type of value returned by the specified operation and op is the
operator being overloaded. The op is preceded by the keyword operator. Operator op is the
function name.
Using friend function:
Non member functions cannot have an access to the private data of a class. However, there
could be a situation where we would like two classes to share a particular function, in such
situation c++ allows the common function to be made friendly with both the classes, thereby
allowing the function to have access to the private data of these classes, such a function
need not be a member of any of these classes.
To make an outside function friendly to a class, we have to simply declare this function as a
friend of the class as shown below:
Class ABC
{
…..
…..
public:
……
friend void xyz(void);
};
The function declaration should be preceded by the keyword friend. The function is defined
elsewhere in the program like a normal c++ function. The function definition does not use
either keyword friend or scope resolution operator ::. The functions that are declared with
the keyword friend are known as friend functions.
A friend function possesses certain special characteristics:

It is not in the scope of the class to which it has been declared as friend.

Since it is not in the scope of the class, it cannot be called using the object of that
class.

It can be invoked like a normal function without the help of any object.

Usually it has the objects as arguments.
Run Time Polymorphism:
An appropriate member function is selected while the program is running. This is known as
run time polymorphism. C++ supports a mechanism known as virtual function to achieve a
run-time polymorphism.
Function Overloading
Function overloading is the practice of declaring the same function with different signatures.
The same function name will be used with different number of parameters and parameters of
different type. But overloading of functions with different return types are not allowed.
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
11
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
In order to overload a function, a different signature should be used for each overloaded
version. A function signature consists of the list of types of its arguments as well as their
order. Here's a set of valid overloaded versions of a function named f:
void
void
void
void
void
void
f(char c, int i);
f(int i, char c);
f(string & s);
f();
f(int i);
f(char c);
For example,let us assume an AddAndDisplay function with different types of
parameters.
//Sample code for function overloading
void AddAndDisplay(int x, int y)
{
cout<<" Integer result: "<<(x+y);
}
void AddAndDisplay(double x, double y)
{
cout<< " Double result: "<<(x+y);
}
void AddAndDisplay(float x, float y)
{
cout<< " Float result: "<<(x+y);
}
Some times when these overloaded functions are called, they might cause ambiguity errors.
This is because the compiler may not be able to decide what signature function should be
called. If the data is type cast properly, then these errors will be resolved easily. Typically,
function overloading is used wherever a different type of data is to be dealt with.
Copy Constructor
Copy constructor is a constructor function with the same name as the class used to
make deep copy of objects.
There are 3 important places where a copy constructor is called.



When an object is created from another object of the same type
When an object is passed by value as a parameter to a function
When an object is returned from a function
If a copy constructor is not defined in a class, the compiler itself defines one. This will ensure
a shallow copy. If the class does not have pointer variables with dynamically allocated
memory, then one need not worry about defining a copy constructor. It can be left to the
compiler's discretion. But if the class has pointer variables and has some dynamic memory
allocations, then it is a must to have a copy constructor.
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
12
10CSL37 Data structures with C/C++ Laboratory
1.
III Sem. CSE
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.
#include<stdio.h>
#include<alloc.h>
struct node
{
float cf;
float px;
int flag;
struct node *link;
};
typedef struct node* NODE;
NODE getnode()
{
NODE temp;
temp=(NODE)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("NO memory\n");
return NULL;
}
return temp;
}
NODE insert_rear(float cf,float x,NODE head)
{
NODE temp,cur;
temp=getnode();
temp->cf=cf;
temp->px=x;
cur=head->link;
while(cur->link!=head)
cur=cur->link;
cur->link=temp;
temp->link=head;
return head;
}
NODE read_poly(NODE head)
{
int i;
float px;
float cf;
printf("Enter the coefficient as -999 to end the polynomial\n");
for(i=1;;i++)
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
13
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
{
printf("Enter the %d term\n",i);
printf("Coeff=");
scanf("%f",&cf);
if(cf==-999) break;
printf("pow x="); scanf("%f",&px);
head=insert_rear(cf,px,head);
}
return head;
}
NODE add_poly(NODE h1, NODE h2, NODE h3)
{
NODE p1,p2;
int x1,x2,cf1,cf2,cf;
p1=h1->link;
while(p1!=h1)
{
x1=p1->px;
cf1=p1->cf;
p2=h2->link;
while(p2!=h2)
{
x2=p2->px;
cf2=p2->cf;
if(x1==x2) break;
p2=p2->link;
}
if(p2!=h2)
{
cf=cf1+cf2;
p2->flag=1;
if(cf!=0) h3=insert_rear(cf,x1,h3);
}
else
h3=insert_rear(cf1,x1,h3);
p1=p1->link;
}
p2=h2->link;
while(p2!=h2)
{
if(p2->flag==0)
{
h3=insert_rear(p2->cf,p2->px,h3);
}
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
14
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
p2=p2->link;
}
return h3;
}
void display(NODE head)
{
NODE temp;
if(head->link==head)
{
printf("Polynomial does not exist\n");
return;
}
temp=head->link;
while(temp!=head)
{
printf("%+5.1fx^%3.1f",temp->cf,temp->px);
temp=temp->link;
}
printf("\n");
}
void main()
{
NODE h1,h2,h3;
h1=getnode();
h2=getnode();
h3=getnode();
clrscr();
h1->link=h1; h2->link=h2; h3->link=h3;
printf("Enter the first polynomial\n\n");
h1=read_poly(h1);
printf("Enter the second polynomial\n\n");
h2=read_poly(h2);
h3=add_poly(h1,h2,h3);
printf("The first polynomial is \n");
display(h1);
printf("The second polynomial is\n");
display(h2);
printf("The sum of two polynomials is \n");
display(h3);
getch();
}
OUTPUT:
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
15
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Discussion Forum:
Date:
Dept. of CSE, CIT, Gubbi- 572 216
Signature of the faculty:
PAGE NO.
16
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
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 13 single character operands
and the binary operators + (plus), - (minus), * (multiply) and / (divide).
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define SIZE 20
#define Operator (-10)
#define Operand (-20)
#define Leftparen (-30)
#define Rightparen (-40)
int top=-1;
char stack[SIZE],infix[SIZE],postfix[SIZE];
void push(char symbol)
{
if(top==(SIZE-1))
printf("\nSTACK OVERFLOW...!!");
else
stack[++top]=symbol;
}
char pop(void)
{
char pop_ele;
if(top==-1)
printf("\nSTACK UNDERFLOW...!!");
else
{
pop_ele=stack[top--];
return pop_ele;
}
}
void infix_to_postfix(void)
{
int i,p,len,type,precedence;
char next;
i=p=0;
len=strlen(infix);
while(i<len)
{
type=get_type(infix[i]);
switch(type)
{
case Leftparen:
push(infix[i]);
break;
case Rightparen:
while((next=pop())!='(') postfix[p++]=next;
break;
case Operand:
postfix[p++]=infix[i];
break;
case Operator:
precedence=get_prec(infix[i]);
while(top>-1 && precedence<=get_prec(stack[top]))
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
17
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
postfix[p++]=pop();
push(infix[i]);
break;
}
i++;
}while(top>-1)
postfix[p++]=pop();
postfix[p]='\0';
}
int get_type(char symbol)
{
switch(symbol)
{
case '(':
return(Leftparen);
case ')':
return(Rightparen);
case '+':
case '-':
case '*':
case '%':
case '/':
return(Operator);
default:
return(Operand);
}}
int get_prec(char symbol)
{
switch(symbol)
{
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '(':
return 0;
default:
return 999;
}
}
void main()
{
int q=0,choice;
do
{
top=-1;
clrscr();
printf("\n\n\n\n\t\t\t******MAIN MENU******");
printf("\n\n\n\n\tENTER 1 --> TO CONVERT INFIX TO POSTFIX");
printf("\n\tENTER 2 --> TO QUIT");
printf("\n\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter an infix expression : ");
fflush(stdin);
gets(infix);
infix_to_postfix();
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
18
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
printf("\nInfix expression : %s",infix);
printf("\nPostfix expression : %s",postfix);
getch();
clrscr();
break;
case 2:
q=1;
printf("\nTHANK YOU.... HAVE A NICE DAY..!!!");
getch();
}
}while(!q);
}
OUTPUT:
******MAIN MENU******
ENTER 1 --> TO CONVERT INFIX TO POSTFIX
ENTER 2 --> TO QUIT
Enter your choice :1
Enter an infix expression :a+b-c*d/e+f-g
Infix expression : a+b-c*d/e+f-g
Postfix expression :ab+cd*e/-f+g-
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
19
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Discussion Forum:
Date:
Dept. of CSE, CIT, Gubbi- 572 216
Signature of the faculty:
PAGE NO.
20
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
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).
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<string.h>
#define size 20
int top=-1;
int stack[size];
int operate(char symb, int oprd1, int oprd2)
{
switch(symb)
{
case '+': return oprd1+oprd2;
case '-': return oprd1-oprd2;
case '*': return oprd1*oprd2;
case '/': return oprd1/oprd2;
case '$':
case '^': return pow(oprd1,oprd2);
}
}
void push(int s[], int d)
{
s[++top]=d;
}
int pop(int s[])
{
int data;
data=s[top--];
return data;
}
void main()
{
int i,ans,oprd1,oprd2,choice,q=0;
char symb, expr[20];
clrscr();
do
{
printf("\n\n\n\t\t\t\t*******MAIN MENU**********");
printf("\n\tPRESS 1 --> TO EVALUATE EXPRESSION");
printf("\n\tPRESS 2 --> TO QUIT");
printf("\n\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the postfix expression : ");
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
21
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
fflush(stdin);
gets(expr);
for(i=0;i<strlen(expr);i++)
{
symb=expr[i];
if(symb>='0' && symb<='9')
push(stack,symb-'0');
else
{
oprd2=pop(stack);
oprd1=pop(stack);
ans=operate(symb,oprd1,oprd2);
push(stack,ans);
}
}
ans=pop(stack);
printf("\nThe result of the postfix expression is : %d",ans);
getch();
clrscr();
break;
case 2:
q=1;
}
}while(!q);
}
OUTPUT:
*******MAIN MENU**********
PRESS 1 --> TO EVALUATE EXPRESSION
PRESS 2 --> TO QUIT
Enter your choice :1
Enter the postfix expression: 45+
Result of the postfix expression is :9
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
22
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Discussion Forum:
Date:
Dept. of CSE, CIT, Gubbi- 572 216
Signature of the faculty:
PAGE NO.
23
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
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
#include<stdio.h>
#include<conio.h>
#define max 5
int f=-1,r=-1,a[max],item;
void qinsert()
{
if(r==max-1)
{
printf("Queue is overflow\n");
return;
}
printf("Enter the item to be inserted\n");
scanf("%d",&item);
if(r==-1)
{
f=f+1;
}
r=r+1;
a[r]=item;
}
void qdelete()
{
if(f==-1)
{
printf("Queue is underflow\n");
return;
}
item=a[f];
f=f+1;
printf("Deleted element from the queue is=%d\n",item);
if(f>r)
{
f=-1;
r=-1;
}
}
void qdisplay()
{
int i;
if(r==-1)
{
printf("Queue is empty\n");
return;
}
printf("The status of the queue is\n");
for(i=f;i<=r;i++)
{
printf("%d\t",a[i]);
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
24
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
}
printf("\n");
}
void main()
{
int k=1,ch;
clrscr();
while(k)
{
printf("Queue operations\n");
printf("******************\n");
printf("\n1->Qinsert\n");
printf("\n2->Qdelete\n");
printf("\n3->Qdisplay\n");
printf("\n4->Exit\n");
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: clrscr();
qinsert();
break;
case 2: clrscr();
qdelete();
break;
case 3: clrscr();
qdisplay();
break;
case 4: k=0;
break;
}
}
getch();
}
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
25
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Discussion Forum:
Date:
Dept. of CSE, CIT, Gubbi- 572 216
Signature of the faculty:
PAGE NO.
26
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
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)
#include<iostream.h>
#include<conio.h>
#define size 25
class EMPLOYEE
//CLASS DEFINITION
{
char emp_num[10], emp_name[25];
float basic, da , it, net_sal;
public:
void getdata();
void netsal();
void display();
};
void EMPLOYEE :: getdata()
//READING THE DATA
{
cout<<"\nenter EMPLOYEE number:";
cin>>emp_num;
cout<<"enter EMPLOYEE name:";
cin>>emp_name;
cout<<"enter basic salary:";
cin>>basic;
}
void EMPLOYEE :: netsal()
//CALCULATING THE NET SALARY
{
da=(.52*basic);
float gsal=basic+da;
it=(.30*gsal);
net_sal=gsal-it;
}
void EMPLOYEE::display() //DISPLAYING THE OUTPUT
{
cout<<"\n\nEMPLOYEE number:"<<emp_num
<<"\nEMPLOYEE name:"<<emp_name
<<"\nnetsalary:"<<net_sal<<endl;
}
void main()
//MAIN FUNCTION
{
clrscr();
EMPLOYEE obj[size];
int n;
cout<<"\nenter number of EMPLOYEEs:";
cin>>n;
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
27
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
for(int i=0;i<n;i++)
{
obj[i].getdata();
obj[i].netsal();
}
for(i=0;i<n;i++)
obj[i].display();
getch();
}
OUTPUT:
enter
enter
enter
enter
number of EMPLOYEEs:2
EMPLOYEE number:CITLEC15
EMPLOYEE name:John
basic salary:8000
enter EMPLOYEE number:CITSL12
enter EMPLOYEE name:Anand
enter basic salary:10000
EMPLOYEE number:CITLEC15
EMPLOYEE name:John
netsalary:8512
EMPLOYEE number:CITSL25
EMPLOYEE name:Anand
netsalary:10640
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
28
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Discussion Forum:
Date:
Dept. of CSE, CIT, Gubbi- 572 216
Signature of the faculty:
PAGE NO.
29
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
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)
#include<iostream.h>
#include<conio.h>
#include<string.h>
class STRING
{
char str[40];
public:
STRING();
// Default Constructor
STRING(char s[]);
// Constructor with parameter
STRING(STRING &s);
// Copy Constructor
STRING operator +(STRING);
friend ostream& operator <<(ostream&, STRING&);
};
STRING::STRING()
{
str[0]='\0';
}
STRING::STRING( char s[])
{
strcpy(str,s);
}
STRING::STRING(STRING &s)
{
strcpy(str,s.str);
}
STRING STRING :: operator +(STRING s1)
{
return(strcat(str,s1.str));
}
ostream& operator <<(ostream& print,STRING &s1)
{
print<<s1.str;
return print;
}
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
30
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
void main()
{
clrscr();
char name1[20],name2[20];
cout<<"Enter two Names as your Wish :";
cin>>name1>>name2;
STRING s1(name1);
//STRING s1="vtu";
cout<<"\nNAME1 : "<<s1;
STRING s2(name2);
//STRING s2="belguam";
cout<<"\nNAME2 : "<<s2;
STRING s3=(s1+s2);
cout<<"\n\nNAME3 : "<<s3;
getch();
}
OUTPUT:
Enter two Names as your Wish :vtu
belgaum
NAME1
NAME2
:
:
vtu
belgaum
NAME3
:
vtubelgaum
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
31
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Discussion Forum:
Date:
Dept. of CSE, CIT, Gubbi- 572 216
Signature of the faculty:
PAGE NO.
32
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
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.
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 <<.
#include<iostream.h>
#include<conio.h>
class STACK
{
int a[100], size, top;
public :
//Constructor with one argument to intialize the stack to -1
//And the Max size of the stack to n that given by the user.
STACK(int n)
{
top=-1;
size=n;
}
void display();
friend STACK operator +(STACK , int);
friend STACK operator --(STACK );
friend int overflow(STACK);
friend int empty( STACK );
friend ostream& operator <<(ostream& ,STACK );
};
STACK operator +(STACK s1, int ele)
{
clrscr();
s1.a[++s1.top]=ele;
return (s1);
}
STACK operator --(STACK s1)
{
clrscr();
cout<<" \nTHE ELEMENT "<<s1.a[s1.top--]
<<" HAS BEEN POPPED OUT OF THE STACK.";
getch();
return(s1);
}
//Functions to check the overflow & underflow
int overflow( STACK s1)
{
if(s1.top==(s1.size-1) )
return(1);
else
return(0);
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
33
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
}
int empty( STACK s1)
{
if(s1.top==-1)
return(1);
else
return(0);
}
ostream& operator <<(ostream& print,STACK s1)
{
if(empty(s1))
{
clrscr();
print<<"\n\tTHE STACK IS EMPTY!!!!!";
getch();
}
else
{
clrscr();
print<<"\nSTACK STATUS :-";
for(int i=s1.top; i>=0;i--)
print<<"\t"<<s1.a[i];
getch();
}
return(print);
}
void main()
{
int choice,element,n;
clrscr();
cout<<"\nEnter the size of the stack : ";
cin>>n;
STACK s1(n);
do
{
clrscr();
cout<<"MENU :-\n(1)PUSH\n(2)POP\n(3)DISPLAY\n(4)EXIT";
cout<<"\nENTER YOUR CHOICE: ";
cin>>choice;
switch(choice)
{
case 1:cout<<"\nENTER THE ELEMENT TO BE PUSHED :";
int element;
cin>>element;
if(overflow(s1))
{
clrscr();
cout<<"\n\t STACK OVERFLOW!!!!! ";
getch();
}
else
s1=s1+element;
cout<<s1;
break;
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
34
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
case 2: if(empty(s1))
{
clrscr();
cout<<"\n THE STACK IS EMPTY!!!!";
getch();
}
else
s1=s1--;
cout<<s1;
break;
case 3: cout<<s1;
break;
case 4: cout<<"\nTHANKYOU!!!!!";
break;
}
}
while(choice!=4);
getch();
}
OUTPUT:
Enter the size of the stack : 5
MENU :-(1)PUSH\n(2)POP\n(3)DISPLAY\n(4)EXIT
ENTER YOUR CHOICE:1
ENTER THE ELEMENT TO BE PUSHED:10
STACK STATUS:10
ENTER YOUR CHOICE:1
ENTER THE ELEMENT TO BE PUSHED:20
STACK STATUS:20 10
ENTER YOUR CHOICE:2
STACK STATUS:10
ENTER YOUR CHOICE:3
STACK STATUS:10
ENTER YOUR CHOICE:4
THANKYOU!!!
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
35
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Discussion Forum:
Date:
Dept. of CSE, CIT, Gubbi- 572 216
Signature of the faculty:
PAGE NO.
36
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
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.
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
struct list
{
int data;
struct list *next;
};
typedef struct list node;
class SLIST
{
node *first;
node *temp;
int count;
public:
SLIST()
{
first=NULL;
count=0;
}
void insertfront(int);
void shownode();
void delfront();
};
void SLIST :: insertfront(int data)
{
temp=new node;
temp->data=data;
temp->next=first;
first=temp;
count++;
}
void SLIST :: delnode()
{
int i;
node *temp=first;
int data;
if(first==NULL)
{
cout<<"THE LIST IS ALREADY EMPTY!!!!!! ";
getch();
return;
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
37
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
}
else
{
cout<<"THE DELETED NODE IS ="<<temp->data<<"\n";
first=temp->next;
free(temp);
count--;
}
}
void SLIST :: shownode()
{
node *temp=first;
cout<<"\nLIST STATUS :-";
if(temp==NULL)
{
cout<<"\nTHE LIST IS EMPTY!!!!";
getch();
}
else
{
cout<<"\nTHE NUMBER OF NODES IN THE LIST IS : "<<count
<<"\nTHE CONTENTS OF THE LIST ARE :- ";
while(temp!=NULL)
{
cout<<temp->data<<"\t";
temp=temp->next;
}
getch();
}
}
void main()
{
SLIST list1;
int flag=0,choice;
int data;
clrscr();
do
{
cout<<"\n\t\tMENU:-\n(1)INSERT NODE \n"
<<"(2)DELETE NODE\n(3)DISPLAY STATUS\n(4)EXIT\n";
cout<<"\nENTER YOUR CHOICE PLEASE(1-4) :";
cin>>choice;
switch (choice)
{
case 1: cout<<"ENTER THE DATA :";
cin>>data;
list1.insertfront(data);
list1.shownode();
break;
case 2:list1.delfront();
list1.shownode();
break;
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
38
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
case 3:list1.shownode();
break;
case 4: cout<<"\tTHANK YOU!!!!";
break;
}
}
while(choice!=4);
getch();
}
OUTPUT:
MENU:(1)INSERT NODE
(2)DELETE NODE
(3)DISPLAY STATUS
(4)EXIT
ENTER YOUR CHOICE PLEASE(1-4)
1
ENTER THE DATA 10
LIST STATUS:NUMBER OF NODES IN THE LIST IS: 1
THE CONTENTS OF THE LIST ARE :- 10
MENU:(1)INSERT NODE
(2)DELETE NODE
(3)DISPLAY STATUS
(4)EXIT
ENTER YOUR CHOICE PLEASE(1-4)
1
ENTER THE DATA 20
LIST STATUS:NUMBER OF NODES IN THE LIST IS: 2
THE CONTENTS OF THE LIST ARE :- 20 10
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
39
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Discussion Forum:
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
40
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
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.
#include<stdio.h>
#include<conio.h>
struct list
{
int row;
int col;
int value;
struct list *next;
};
typedef struct list* LIST;
LIST create_node(int,int,int,LIST);
void search(LIST,int);
void display(LIST);
LIST first=NULL;
void main()
{
int r,c,i,j,ele,search_ele;
clrscr();
printf("\nenter the order of the sparse matrix");
scanf("%d%d",&r,&c);
printf("\nenter the elements in the sparse matrix(mostly zeroes)");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("\n%d row and %d column ",i,j);
scanf("%d",&ele);
if(ele!=0)
first=create_node(ele,i,j,first);
}
}
display(first);
printf("Enter the element to be searched\n");
scanf("%d",&search_ele);
search(first,search_ele);
getch();
}
LIST getnode(void)
{
LIST x;
x=(LIST) malloc(sizeof(struct list));
if(x==NULL)
{
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
41
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
printf("\nNO MEMORY!...!");
getch();
exit(1);
}
return (x);
}
LIST create_node(int item,int i,int j,LIST first)
{
LIST temp,cur;
temp=getnode();
temp->value=item;
temp->row=i;
temp->col=j;
temp->next=NULL;
if(first==NULL) return temp;
cur=first;
while(cur->next!=NULL)
cur=cur->next;
cur->next=temp;
return first;
}
void display(LIST first)
{
LIST temp;
if(first==NULL)
{
printf("List is empty and no elements in the sparse matrix\n");
return;
}
temp=first;
while(temp!=NULL)
{
printf("row=%d\t",temp->row);
printf("col=%d\t",temp->col);
printf("value=%d\n",temp->value);
temp=temp->next;
}
}
void search(LIST first,int search_ele)
{
int i=0,j=0;
LIST temp=first;
while(temp!=NULL)
{
if(search_ele==temp->value)
{
printf("Search Successfull at row=%d and col=%d\n",temp->row,temp->col);
}
temp=temp->next;
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
42
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
}
}
OUTPUT:
Enter the order of the matrix
33
Enter the matrix elements
0 row and 0 column 0
0 row and 1 column 0
0 row and 2 column 0
1 row and 1 column 1
1 row and 2 column 2
1 row and 3 column 3
2 row and 0 column 4
2 row and 1 column 0
2 row and 2 column 0
row= 1 col=0 value=1
row= 1 col=1 value=2
row= 1 col=2 value=3
row= 1 col=0 value=4
Enter the element to be searched
2
Search successful at row=1 and col=1
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
43
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Discussion Forum:
Date:
Dept. of CSE, CIT, Gubbi- 572 216
Signature of the faculty:
PAGE NO.
44
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
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.
#include<stdio.h>
#include<conio.h>
void buildheap(int*,int);
void display(int*,int);
void main()
{
int a[20],n,i,j,k;
clrscr();
printf("Enter the number of elements to sort : ");
scanf("%d",&n);
printf("Enter the elements :");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
buildheap(a,i);
display(a,i);
}
getch();
}
// Function used to build heap using bottom-up heap construction approach.
void buildheap(int *a,int i)
{
int v=a[i];
while((i>1)&&(a[i/2]<v))
{
a[i]=a[i/2];
i=i/2;
}
a[i]=v;
}
void display(int *a,int n)
{
int i=1;
for(i=1;i<=n;i++)
printf("%4d",a[i]);
}
OUTPUT:
Enter the number of elements to sort :5
Enter the elements :3 6 2 3 1
76231
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
45
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Discussion Forum:
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
46
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
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:
a. Create a doubly linked list by adding each node at the front.
b. Insert a new node to the left of the node whose key value is read as an
input.
c. Delete the node of a given data if it is found, otherwise display
appropriate message.
d. Display the contents of the list.
(Note: Only either (a,b and d) or (a, c and d) may be asked in the
examination)
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct list
{
int info;
struct list *llink,*rlink;
};
typedef struct list* NODE;
NODE getnode()
{
NODE temp;
temp=(NODE)malloc(sizeof(struct list));
if(temp==NULL)
{
printf("NO memory\n");
return NULL;
}
return temp;
}
NODE insert_front(NODE head, int info)
{
NODE temp,cur;
temp=getnode();
temp->info=info;
cur=head->rlink;
temp->llink=head;
head->rlink=temp;
temp->rlink=cur;
cur->llink=temp;
return head;
}
NODE insert_left(NODE head,int key)
{
int data;
NODE cur,prev,temp;
if(head->rlink==head&&head->llink==head)
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
47
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
{
printf("No nodes in the list\n");
return head;
}
cur=head->rlink;
while(cur!=head)
{
if(cur->info==key) break;
cur=cur->rlink;
}
if(cur==head)
{
printf("NO key node found\n");
return head;
}
temp=getnode();
printf("Enter the data for new node to be inserted left side\n");
scanf("%d",&data);
temp->info=data;
prev=cur->llink;
prev->rlink=temp;
temp->llink=temp;
temp->rlink=cur;
cur->llink=temp;
return head;
}
NODE delete_node(NODE head,int key)
{
NODE cur,prev,temp,next;
if(head->rlink==head&&head->llink==head)
{
printf("No nodes in the list\n");
return head;
}
cur=head->rlink;
while(cur!=head)
{
if(cur->info==key) break;
cur=cur->rlink;
}
if(cur==head)
{
printf("NO key node found\n");
return head;
}
prev=cur->llink;
next=cur->rlink;
prev->rlink=next;
next->llink=prev;
printf("The deleted node is=%d\n",cur->info);
free(cur);
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
48
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
return head;
}
void display(NODE head)
{
NODE cur;
if(head->rlink==head&&head->llink==head)
{
printf("No nodes in the list\n");
return;
}
cur=cur->rlink;
while(cur!=head)
{
printf("%d\t",cur->info);
cur=cur->rlink;
}
}
void main()
{
int data,k=1,ch;
NODE head;
head=getnode();
head->rlink=head->llink=head;
clrscr();
while(k)
{
printf("Enter
printf("Enter
printf("Enter
printf("Enter
printf("Enter
1-> insert node\n");
2-> insert node at left\n");
3-> delete node\n");
4-> display\n");
5->exit\n");
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter the data to be inserted\n");
scanf("%d",&data);
head=insert_front(head,data);
display(head);
break;
case 2: printf("Enter the key to be found\n");
scanf("%d",&data);
head=insert_left(head,data);
display(head);
break;
case 3: printf("Enter the data to be deleted\n");
scanf("%d",&data);
head=delete_node(head,data);
display(head);
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
49
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
break;
case 4: display(head);
break;
case 5: k=0;
break;
}
}
getch();
}
OUTPUT:
Discussion Forum:
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
50
10CSL37 Data structures with C/C++ Laboratory
Date:
Dept. of CSE, CIT, Gubbi- 572 216
III Sem. CSE
Signature of the faculty:
PAGE NO.
51
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
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 number of
days is
an integer.
#include<iostream.h>
#include<conio.h>
int d[13];
class DATE
{
private:
int dd;
int mm;
int yy;
public:
DATE()
{
d[1]=31, d[2]=28, d[3]=31, d[4]=30, d[5]=31, d[6]=30;
d[7]=31, d[8]=30, d[9]=31, d[10]=31, d[11]=30, d[12]=31;
}
void getdata();
int operator-(DATE);
DATE operator+(int);
friend ostream & operator << (ostream &,DATE);
};
void DATE :: getdata()
{
cin>>dd>>mm>>yy;
}
int DATE :: operator - (DATE d2)
{
int days=0, leap=0, days1=0, days2=0;
if((yy == d2.yy) && (mm == d2.mm))
{
days = dd - d2.dd;
return (days);
}
if((yy==d2.yy) && (mm !=d2.mm))
{
for(int i=d2.mm; i< mm; i++)
days+=d[i];
if((yy % 4 == 0) && (mm > 2) && (d2.mm <= 2))
leap++;
days+=leap;
days = days - d2.dd + dd;
return (days);
}
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
52
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
for(int i=1; i< mm; i++)
days1+=d[i];
days1+=dd;
for(i=d2.mm;i<=12;i++)
days2+=d[i];
days2-=d2.dd;
if((d2.yy % 4 == 0) && (d2.mm <=2))
leap++;
if(yy%4==0 && mm>2)
leap++;
int yy1 = d2.yy + 1;
for(i=yy1; i<yy; i++)
if(i%4 == 0)
leap++;
long int years = (yy - yy1) * 365 + leap;
return (years + days1 + days2);
DATE DATE :: operator + (int n)
{
for(int i=1; i<=n; i++)
{
dd++;
if(dd > d[mm])
{
mm++;
dd = 1;
}
if(mm > 12)
{
yy++;
mm = 1;
dd = 1;
}
}
return *this;
}
ostream & operator << (ostream & out ,DATE e)
{
out<<e.dd<<" / "<<e.mm<<" / "<<e.yy;
return out;
}
void main()
{
DATE d1,d2;
clrscr();
cout<<"\n\n\t\t ENTER THE FIRST DATE : ";
d1.getdata();
cout<<"\n\n\t\tENTER THE SECOND DATE : ";
d2.getdata();
int result=d1-d2;
cout<<"\n\n\t\t DIFFERENCE IS : "<<result;
int ndays;
cout<<"\n\n\t\tENTER THE NUM OF DAYS : ";
cin>>ndays;
d1=d1+ndays;
cout<<"UPDATED DATE IS :"<<d1;
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
53
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
getch();
}
OUTPUT:
ENTER THE FIRST DATE : 22 3 2008
ENTER THE SECOND DATE : 22 2 2008
DIFFERENCE IS : 29
ENTER THE NUM OF DAYS : 22
UPDATED DATE IS :13 / 4 / 2008
ENTER THE FIRST DATE : 2 2 2009
ENTER THE SECOND DATE : 2 2 2008
DIFFERENCE IS : 366
ENTER THE NUM OF DAYS :23
UPDATED DATE IS : 25 / 2 / 2009
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
54
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Discussion Forum:
Date:
Dept. of CSE, CIT, Gubbi- 572 216
Signature of the faculty:
PAGE NO.
55
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
13.Design, develop, and execute a program in C++ to create a class called OCTAL,
which has the characteristics of an octal number. 15 Implement the following
operations by writing an appropriate constructor and an overloaded operator +.
#include<iostream.h>
#include<math.h>
#include<conio.h>
class octal
{
private :
int a;
public:
octal(int x)
{
a=dec_oct(x);
}
int operator +(int k)
{
int y,k1;
k1=oct_dec(a);
//convaert the octal int decimal
y= k+k1;
//add the decimal numbers
return(y);
//return the octal equivalent of the integer result
}
int dec_oct(int);
int oct_dec(int);
friend ostream &operator<<(ostream &s,octal o);
};
int octal::dec_oct(int n)
{
int sum=0,i=0,rem;
while(n>0)
{
rem=n%8;
sum += rem*(int)pow((double)10,i);
i++;
n=n/8;
}
return sum;
}
int octal::oct_dec(int n)
{
int sum=0,i=1,rem;
while(n>0)
{
rem=n%10;
sum += rem*i;
i=i*8;
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
56
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
n=n/10;
}
return sum;
}
ostream &operator<<(ostream &s ,octal o)
{
s<<o.a;
return s;
}
void main()
{
int x,k;
int y;
clrscr();
cout<<"\n ENTER THE INTEGER : ";
cin>>x;
octal h=x;
cout<<"\n OCTAL EQUIVALENT OF DECIMAL NUMBER :"<<h;
cout<<"\n ENTER THE VALUE OF K : ";
cin>>k;
y=h+k;
cout<<"\n\n OCTAL EQUIVALENT OF RESULT IS : "<<y<<endl;
getch();
}
OUTPUT:
ENTER THE INTEGER : 54
OCTAL EQUIVALENT OF DECIMAL NUMBER :66
ENTER THE VALUE OF K : 44
OCTAL EQUIVALENT OF INTEGER RESULT IS : 98
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
57
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Discussion Forum:
Date:
Dept. of CSE, CIT, Gubbi- 572 216
Signature of the faculty:
PAGE NO.
58
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
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.
#include<iostream.h>
#include<conio.h>
struct dlist
{
int info;
struct dlist *left;
struct dlist *right;
};
typedef struct dlist node;
class BIN_TREE
{
node *root;
public:
BIN_TREE()
{
root=NULL;
}
void gettree();
void preorder(node*,int);
void postorder(node*,int);
void inorder(node*,int);
};
void BIN_TREE :: gettree()
{
int c;
node *newnode;
node *prev=NULL;
int i,n,ele;
cout<<"ENTER THE NO. OF NODES IN THE TREE :";
cin>>n;
cout<<"\nEnter the element :";
for(i=1;i<=n;i++)
{
newnode= new node;
clrscr();
cin>>ele;
newnode->info=ele;
newnode->left=newnode->right=NULL;
if(root==NULL)
{
root=newnode;
continue;
}
node *temp=root;
while(temp!=NULL)
{
if(ele<temp->info)
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
59
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
{
prev=temp;
temp=temp->left;
}
else
{
prev=temp;
temp=temp->right;
}
}
if(ele<prev->info)
prev->left=newnode;
else
prev->right=newnode;
}
}
void BIN_TREE :: preorder( node* temp,int c)
{
if(c==0)
temp=root;
c++;
if(temp!=NULL)
{
cout<<"\t"<<temp->info;
preorder(temp->left,c);
preorder(temp->right,c);
}
}
void BIN_TREE::postorder(node* temp,int c)
{
if(c==0)
temp=root;
c++;
if(temp!=NULL)
{
postorder(temp->left,c);
postorder(temp->right,c);
cout<<"\t"<<temp->info;
}
}
void BIN_TREE::inorder(node *temp,int c)
{
if(c==0)
temp=root;
c++;
if(temp!=NULL)
{
inorder(temp->left,c);
cout<<"\t"<<temp->info;
inorder(temp->right,c);
}
}
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
60
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
void main()
{
BIN_TREE t1;
int c=0;
clrscr();
t1.gettree();
clrscr();
cout<<"\n\nPREORDER DISPLAY :- ";
t1.preorder(NULL,c);
cout<<"\n\nPOSTORDER DISPLAY :- ";
t1.postorder(NULL,c);
cout<<"\n\nINORDER DISPLAY :- ";
t1.inorder(NULL,c);
getch();
}
OUTPUT:
------ENTER THE NO. OF NODES IN THE TREE :
Enter the element : 1 2 3 5 4
PREORDER DISPLAY :- 1
2
POSTORDER DISPLAY :- 4
INORDER DISPLAY :-
1
3
5
2
5
5
3
3
4
2
4
1
5
ENTER THE NO. OF NODES IN THE TREE : 4
Enter the element : 9 7 3 5
PREORDER DISPLAY :- 9
7
3
5
POSTORDER DISPLAY :- 5
3
7
9
INORDER DISPLAY :3
5
7
9
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
61
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Discussion Forum:
Date:
Dept. of CSE, CIT, Gubbi- 572 216
Signature of the faculty:
PAGE NO.
62
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
Text Book:
1. Horowitz, Sahni, Anderson-Freed: Fundamentals of Data Structures
in C, 2nd Edition, Universities Press, 2007.
2. Herbert Schildt: The Complete Reference C++, 4th Edition, Tata
McGraw Hill, 2003
Reference Books:
1. Yedidyah, Augenstein, Tannenbaum: Data Structures Using C and
C++, 2nd Edition, Pearson Education, 2003.
2. Debasis Samanta: Classic Data Structures, 2nd Edition, PHI, 2009.
3. Richard F. Gilberg and Behrouz A. Forouzan: Data Stru
Stanley B.Lippmann, Josee Lajore: C++ Primer, 4th Edition, Pearson
Education, 2005.
4. Paul J Deitel, Harvey M Deitel: C++ for Programmers, Pearson
Education, 2009.
5. K R Venugopal, Rajkumar Buyya, T Ravi Shankar: Mastering C++ Tata
McGraw Hill, 1999
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
63
10CSL37 Data structures with C/C++ Laboratory
III Sem. CSE
VIVA QUESTIONS:
1.
What is the need of data structures in programming ?
2.
Which are the basic data structures?
3.
Differentiate between data structures and data types?
4.
Differentiate between linear and nonlinear data structures?
5.
What do you mean by pointer?
6.
How to add two polynomials?
7.
What is stack data structure?
8.
What is queue data structure?
9.
What are the applications of stack?
10.
What are the applications of queue?
11.
What is circular queue?
12.
What is linked list ?
13.
What are the applications of linked list?
14.
What are trees?
15.
Differentiate graph and tree?
16.
Differentiate binary tree and binary search tree?
17.
Types of binary trees.
18.
What are the differences between Procedural & Object Oriented Programming?
19.
What are all the concepts to recognize a language as an OOPL?
20.
Distinguish between Object & Class.
21.
What is data abstraction, data hiding & data encapsulation?
22.
List out the advantages of OOP.
23.
What is inheritance & polymorphism?
24.
What is function prototype? Why it is required is it necessary for C++.
25.
Define the following functions.
26.

Inline functions.

Friend function.
Differentiate between the following

Function overloading v/s Operator over loading

Inline function & a regular function.

Friend member function & member function of a class.

Class & a structure.

Macro & inline function.

Static & Dynamic binding.
27.
Advantages & Disadvantages of inline function.
28.
What is reference variable. Advantages of using reference variables?.
29.
What are the key words that are present in c++ but not in C?.
30.
What are the difference between C & C++?.
31.
What are the rules we have to following while using default arguments?
32.
What are the advantages of using default arguments?
33.
What is friend function? Why it is required. Do friends violate encapsulation?
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
64
10CSL37 Data structures with C/C++ Laboratory
34.
Define static & static member of a class.
35.
Define New & Delete operator.
a.
III Sem. CSE
Define the following.

Constructor & Destructor when they are executed.

Copy constructor & Parameterized constructor.
36.
List out the characteristics of a constructor.
37.
Why inheritance is required?.
38.
What are the diff. types of inheritance?
39.
Difference between Public, Private & Protected access specifier.
40.
Define Virtual Function. Why it is required?.
41.
What is virtual base class? Why it is required?.
42.
What are the changes we can notice for C to C++?
43.
What is this pointer?
44.
Is there any difference in typecasting compared to that of C.
45.
Explain some ways that ambiguity can introduced when over loading functions.
46.
What are default arguments? Why it is required.
47.
How does friend operator function differ from member operator?
48.
Why operator to be overloaded?
49.
What are the different situations we can use const keyword.
50.
What is scope resolution operator? Why it is required.
51.
What are the different types of constructors?
52.
How does the C++ compiler resolves the conflicts in overloaded functions.
53.
What is the difference between declaration and definition?
54.
Which are all the operators that we can't overload?
55.
Define function template & class template.
56.
What are the differences between function overloading, operator overloading & Function
template.
57.
What is template instantiation?
58.
What is a pure virtual function?
59.
Why name of our language is C++ why not ++C.
60.
Difference between virtual base class with Virtual function.
61.
Differences between Static binding and dynamic binding.
62.
Difference between realloc() and free?
63.
What are generic functions and generic classes?
64.
What is the function of 'this' operator ?
65.
What is namespace?
66.
What is difference between function overloading and function overriding?
…… Good Luck ……
Dept. of CSE, CIT, Gubbi- 572 216
PAGE NO.
65