SlideShare una empresa de Scribd logo
1 de 166
Dr.C.Naveeth Babu
Department of CS
Kristu Jayanti College, Bangalore
A Queue is a linear structure which follows a particular
order in which the operations are performed.
The order is First In First Out (FIFO).
A good example of a queue is any queue of consumers
for a resource where the consumer that came first is
served first.
The difference between stacks and queues is in
removing.
In a stack we remove the item the most recently added;
in a queue, we remove the item the least recently
added.
A real-world example of queue can be a single-lane one-way road,
where the vehicle enters first, exits first. More real-world examples
can be seen as queues at the ticket windows and bus-stops.
Basic Operations
enqueue() − add (store) an item to the queue.
dequeue() − remove (access) an item from the queue.
 Queues maintain two data pointers, front and rear.
Therefore, its operations are comparatively difficult to
implement than that of stacks.
 The following steps should be taken to enqueue (insert) data
into a queue −
 Step 1 − Check if the queue is full.
 Step 2 − If the queue is full, produce overflow error and
exit.
 Step 3 − If the queue is not full, increment rear pointer to
point the next empty space.
 Step 4 − Add data element to the queue location, where the
rear is pointing.
 Step 5 − return success.
procedure enqueue(data)
if queue is full
return overflow
endif
rear ← rear + 1
queue[rear] ← data
return true
end procedure
int enqueue(int data)
if(isfull())
return 0;
rear = rear + 1;
queue[rear] = data;
return 1;
end procedure
 Accessing data from the queue is a process of two tasks −
access the data where front is pointing and remove the data
after access. The following steps are taken to
perform dequeue operation −
 Step 1 − Check if the queue is empty.
 Step 2 − If the queue is empty, produce underflow error and
exit.
 Step 3 − If the queue is not empty, access the data
where front is pointing.
 Step 4 − Increment front pointer to point to the next
available data element.
 Step 5 − Return success.
procedure dequeue
if queue is empty
return underflow
end if
data = queue[front]
front ← front + 1
return true
end procedure
int dequeue()
{
if(isempty())
return 0;
int data = queue[front];
front = front + 1;
return data;
}
We can easily represent queue by using linear arrays.
There are two variables i.e. front and rear, that are
implemented in the case of every queue.
Front and rear variables point to the position from
where insertions and deletions are performed in a
queue.
Initially, the value of front and queue is -1 which
represents an empty queue.
Array representation of a queue containing 5 elements
along with the respective values of front and rear, is
shown in the following figure.
 A simple queue is the most basic queue. In this
queue, the enqueue operation takes place at the rear,
while the dequeue operation takes place at the front:
 Its applications are process scheduling, disk scheduling,
memory management, IO buffer, pipes, call center
phone systems, and interrupt handling.
 Circular Queue is a linear data structure in which the
operations are performed based on FIFO (First In First
Out) principle and the last position is connected back to
the first position to make a circle. It is also called ‘Ring
Buffer’.
 In a circular queue, all nodes are treated as circular.
Last node is connected back to the first node.
 Circular queue is also called as Ring Buffer.
 It is an abstract data type.
 Circular queue contains a collection of data which
allows insertion of data at the end of the queue and
deletion of data at the beginning of the queue.
circular queue
 A deque, also known as a double-ended queue, is an
ordered collection of items similar to the queue. It has
two ends, a front and a rear, and the items remain
positioned in the collection.
 What makes a deque different is the unrestrictive nature
of adding and removing items. New items can be added
at either the front or the rear. Likewise, existing items
can be removed from either end.
 The deque abstract data type is defined by the
following structure and operations.
 A deque is structured, as described above, as an ordered
collection of items where items are added and removed
from either end, either front or rear.
 The deque operations are given below.
 Deque() creates a new deque that is empty. It needs no
parameters and returns an empty deque.
 add_front(item) adds a new item to the front of the deque.
It needs the item and returns nothing.
 add_rear(item) adds a new item to the rear of the deque. It
needs the item and returns nothing.
 remove_front() removes the front item from the deque. It
needs no parameters and returns the item. The deque is
modified.
 remove_rear() removes the rear item from the deque. It
needs no parameters and returns the item. The deque is
modified.
 is_empty() tests to see whether the deque is empty. It needs
no parameters and returns a boolean value.
 size() returns the number of items in the deque. It needs no
parameters and returns an integer.
Deque Operation Deque Contents
d.is_empty() []
d.add_rear(4) [4]
d.add_rear('dog') ['dog', 4]
d.add_front('cat') ['dog', 4, 'cat']
d.add_front(True) ['dog', 4,'cat', True]
d.size() ['dog', 4, 'cat', True]
d.is_empty() ['dog', 4, 'cat', True]
d.add_rear(8.4) [8.4, 'dog', 4, 'cat',True]
d.remove_rear() ['dog', 4, 'cat', True]
d.remove_front() `['dog', 4, 'cat']
 A priority queue is a special type of queue in
which each element is associated with
a priority and is served according to
its priority.
 Generally, the value of the element itself is
considered for assigning the priority.
 For example, The element with the highest
value is considered as the
highest priority element.
 Job Scheduling on a shared computer
 Event – driven simulation
Basic Operations
 insert / enqueue − add an item to the rear of the queue.
 remove / dequeue − remove an item from the front of
the queue.
There is few more operations supported by queue which
are following.
 Peek − get the element at front of the queue.
 isFull − check if queue is full.
 isEmpty − check if queue is empty.
 Whenever an element is inserted into queue, priority
queue inserts the item according to its order. Here we're
assuming that data with high value has low priority.
 A data structure is a particular way of organizing data
in a computer so that it can be used effectively.
 For example, we can store a list of items having the
same data-type using the array data structure.
There are two types of data structures:
 Primitive data structure
 Non-primitive data structure
Primitive Data structure
 The primitive data structures are primitive data types. The
int, char, float, double, and pointer are the primitive data
structures that can hold a single value.
Non-Primitive Data structure
The non-primitive data structure is divided into two types:
 Linear data structure
 Non-linear data structure
Linear Data Structure
 The arrangement of data in a sequential manner is
known as a linear data structure. The data structures
used for this purpose are Arrays, Linked list, Stacks,
and Queues. In these data structures, one element is
connected to only one another element in a linear form.
Non Linear Data Structure
 When one element is connected to the 'n' number of
elements known as a non-linear data structure. The best
example is trees and graphs. In this case, the elements
are arranged in a random manner.
Data structures can also be classified as:
 Static data structure: It is a type of data structure
where the size is allocated at the compile time.
Therefore, the maximum size is fixed.
 Dynamic data structure: It is a type of data structure
where the size is allocated at the run time. Therefore,
the maximum size is flexible.
The major or the common operations that can be performed
on the data structures are:
 Searching: We can search for any element in a data
structure.
 Sorting: We can sort the elements of a data structure either
in an ascending or descending order.
 Insertion: We can also insert the new element in a data
structure.
 Updation: We can also update the element, i.e., we can
replace the element with another element.
 Deletion: We can also perform the delete operation to
remove the element from the data structure.
The pointer in C language is a variable which
stores the address of another variable.
Consider the following example to define a
pointer which stores the address of an integer.
int n = 10;
int*p = &n; // Variable p of type pointer is pointing to
the address of the variable n of type integer.
 The pointer in c language can be declared
using * (asterisk symbol).
Syntax
data_type * pointer_variable_name;
Example
int *a;//pointer to int
char *c;//pointer to char
int *ptr_thing; /* pointer to an integer */
int *ptr1,thing;/* ptr1 is a pointer to type integer and
thing is an integer variable */
double *ptr2; /* pointer to a double */
float *ptr3; /* pointer to a float */
char *ch1 ; /* pointer to a character */
float *ptr, variable;/*ptr is a pointer to type float and
variable is an ordinary float variable */
Operator Meaning
* Serves 2 purpose
1.Declaration of a pointer
2.Returns the value of the referenced
variable
& Serves only 1 purpose - Returns the
address of a variable
 Static Memory is allocated for declared variables by the
compiler.
 Static memory allocation is an allocation technique
which allocates a fixed amount of memory during
compile time and the operating system internally uses a
data structure known as Stack to manage this.
 The memory is allocated during compile time.
 Variables get allocated permanently
 Allocation is done before program execution
 It uses the data structure called stack for implementing
static allocation
 Less efficient
 There is no memory reusability
All the variables in the program below are statically
allocated.
void play
{ int a;
}
int main()
{
int b;
int c[10];
}
In this type of allocation, you strictly allocate memory
for your data at compile time.
 Simplicity of usage.
 Efficient execution time.
 Need not worry about memory allocation/re-
allocation/freeing of memory
 Variables remain permanently allocated.
 Main disadvantage is wastage of memory.
 Memory can't be freed when it is no longer needed.
 Memory allocation done at the time of execution(run
time) is known as dynamic memory allocation.
 Functions calloc() and malloc() support allocating
dynamic memory.
 Data structures can grow and shrink according to the
requirement.
◦ We can allocate (create) additional storage whenever we need
them.
◦ We can de-allocate (free/delete) dynamic space whenever we
are
done with them.
 Dynamic Allocation is done at run time.
 As the memory is allocated during runtime, it requires
more time.
 Memory needs to be freed by the user when done. This
is important as it is more likely to turn into bugs that
are difficult to find.
S.No Static Memory Allocation Dynamic Memory Allocation
1
In the static memory allocation,
variables get allocated permanently.
In the Dynamic memory allocation,
variables get allocated only if your
program unit gets active.
2
Static Memory Allocation is done
before program execution.
Dynamic Memory Allocation is done
during program execution.
3
It uses stack for managing the static
allocation of memory
It uses heap for managing the
dynamic allocation of memory
4 It is less efficient It is more efficient
5
In Static Memory Allocation, there is
no memory re-usability
In Dynamic Memory Allocation,
there is memory re-usability and
memory can be freed when not
required
6
In static memory allocation, once the
memory is allocated, the memory size
can not change.
In dynamic memory allocation, when
memory is allocated the memory size
can be changed.
7
In this memory is allocated at
compile time.
In this memory is allocated at run time.
8
In this allocated memory
remains from start to end of
the program.
In this allocated memory can be released at
any time during the program.
9
Example: This static memory
allocation is generally used
for array.
Example: This dynamic memory allocation
is generally used for linked list.
malloc() - The name "malloc" stands for memory
allocation.
The malloc() function reserves a block of memory of the
specified number of bytes.
Syntax of malloc()
ptr = (castType*) malloc(size);
Example
ptr = (float*) malloc (100 * sizeof(float));
The above statement allocates 400 bytes of memory.
It's because the size of float is 4 bytes.
And, the pointer ptr holds the address of the first byte in
the allocated memory.
 Calloc - The name "calloc" stands for contiguous
allocation.
 The malloc() function allocates memory and leaves the
memory uninitialized, whereas the calloc() function
allocates memory and initializes all bits to zero.
Syntax of calloc()
 ptr = (castType*)calloc(n, size);
Example:
 ptr = (float*) calloc(25, sizeof(float));
The above statement allocates contiguous space in
memory for 25 elements of type float.
 realloc() - the dynamically allocated memory is
insufficient or more than required, you can change the
size of previously allocated memory using
the realloc() function.
Syntax of realloc()
ptr = realloc(ptr, x);
Here, ptr is reallocated with a new size x.
 A linked list is a sequence of data structures, which are
connected together via links.
 Linked List is a sequence of links which contains items.
 Each link contains a connection to another link.
 Linked list is the second most-used data structure after
array.
 Linked List contains a link element called first or head.
 Each link carries a data field(s) and a link field called
next.
 Each link is linked with its next link using its next link.
 Last link carries a link as null to mark the end of the
list.
Following are the various types of linked list.
 Simple Linked List − Item navigation is forward only.
 Doubly Linked List − Items can be navigated forward
and backward.
 Circular Linked List − Last item contains link of the
first element as next and the first element has a link to
the last element as previous.
Following are the basic operations supported by a list.
 Insertion − Adds an element at the beginning of the
list.
 Deletion − Deletes an element at the beginning of the
list.
 Display − Displays the complete list.
 Search − Searches an element using the given key.
 Delete − Deletes an element using the given key.
Dynamic Data Structure
 Linked list is a dynamic data structure so it can grow
and shrink at runtime by allocating and deallocating
memeory. So there is no need to give initial size of
linked list.
Insertion and Deletion
 Insertion and deletion of nodes are really easier.
No Memory Wastage
 As size of linked list can increase or decrease at run
time so there is no memory wastage.
Implementation
 Data structures such as stack and queues can be easily
implemented using linked list.
Memory Usage
 More memory is required to store elements in linked list as
compared to array. Because in linked list each node
contains a pointer and it requires extra memory for itself.
Traversal
 Elements or nodes traversal is difficult in linked list.
We can not randomly access any element as we do in array
by index. For example if we want to access a node at
position n then we have to traverse all the nodes before it.
So, time required to access a node is large.
Reverse traversing
 Reverse traversing in a linked list is very difficult,
because it requires more memory for the pointer.
 It is used to maintain directory names.
 The linked list can perform arithmetic operations in the
long integer.
 We can also use it to next and previous images in the
image viewer.
 With the help of the linked list, we can move songs
back and forth in the music player.
 The linked list is also used for undo in word and
Photoshop applications.
Insertion Operation
Adding a new node in linked list is a more than one step
activity.
We shall learn this with diagrams here. First, create a
node using the same structure and find the location where
it has to be inserted.
Imagine that we are inserting a node B (NewNode),
between A (LeftNode) and C (RightNode).
NewNode.next −> RightNode;
Now, the next node at the left should point to the new node.
LeftNode.next −> NewNode;
This will put the new node in the middle of the two.
The new list should look like this −
/* inserts a new node on the front of the list. */
void push(struct Node** head_ref, int new_data)
{
/* 1. allocate node */
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
/* 2. put in the data */
new_node->data = new_data;
/* 3. Make next of new node as head */
new_node->next = (*head_ref);
/* 4. move the head to point to the new node */
(*head_ref) = new_node;
}
 Deletion Operation
Deletion is also a more than one step process. We shall
learn with pictorial representation. First, locate the target
node to be removed, by using searching algorithms.
 The left (previous) node of the target node now should
point to the next node of the target node −
LeftNode.next −> TargetNode.next;
 This will remove the link that was pointing to the target
node. Now, using the following code, we will remove
what the target node is pointing at.
 This will remove the link that was pointing to the target
node. Now, using the following code, we will remove
what the target node is pointing at.
TargetNode.next −> NULL;
 Doubly linked list is a type of linked list in which each
node apart from storing its data has two links.
 The first link points to the previous node in the list and
the second link points to the next node in the list.
 The first node of the list has its previous link pointing
to NULL similarly the last node of the list has its next
node pointing to NULL.
 Implementation of Doubly Linked List
First we define the node.
struct node
{
int data; // Data
node *prev; // A reference to the previous node
node *next; // A reference to the next node
};
Now we define our class Doubly Linked List. It has the
following methods:
 add_front: Adds a new node in the beginning of list
 add_after: Adds a new node after another node
 add_before: Adds a new node before another node
 add_end: Adds a new node in the end of list
 delete: Removes the node
 forward_traverse: Traverse the list in forward
direction
 backward_traverse: Traverse the list in backward
direction
 A doubly linked list containing three nodes
having numbers from 1 to 3 in their data
part, is shown in the following image.
 Insertion in doubly linked list at beginning
Algorithm :
Step 1: IF ptr = NULL
Write OVERFLOW
Go to Step 9
[END OF IF]
Step 2: SET NEW_NODE = ptr
Step 3: SET ptr = ptr -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET NEW_NODE -> PREV = NULL
Step 6: SET NEW_NODE -> NEXT = START
Step 7: SET head -> PREV = NEW_NODE
Step 8: SET head = NEW_NODE
Step 9: EXIT
 Deletion in doubly linked list at the end
Step 1: IF HEAD = NULL
Write UNDERFLOW
Go to Step 7
[END OF IF]
Step 2: SET TEMP = HEAD
Step 3: REPEAT STEP 4 WHILE TEMP->NEXT != NULL
Step 4: SET TEMP = TEMP->NEXT
[END OF LOOP]
Step 5: SET TEMP ->PREV-> NEXT = NULL
Step 6: FREE TEMP
Step 7: EXIT
 A circular linked list is a sequence of elements in
which every element has a link to its next element in
the sequence and the last element has a link to the
first element.
Operations
In a circular linked list, we perform the following
operations...
 Insertion
 Deletion
 Display
Step 1: IF PTR = NULL
Write OVERFLOW
Go to Step 11
[END OF IF]
Step 2: SET NEW_NODE = PTR
Step 3: SET PTR = PTR -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET TEMP = HEAD
Step 6: Repeat Step 8 while TEMP -> NEXT != HEAD
Step 7: SET TEMP = TEMP -> NEXT
[END OF LOOP]
Step 8: SET NEW_NODE -> NEXT = HEAD
Step 9: SET TEMP → NEXT = NEW_NODE
Step 10: SET HEAD = NEW_NODE
Step 11: EXIT
 Deletion in Circular singly linked list at the end
Algorithm
Step 1: IF HEAD = NULL
Write UNDERFLOW
Go to Step 8
[END OF IF]
Step 2: SET PTR = HEAD
Step 3: Repeat Steps 4 and 5 while PTR -> NEXT != HEAD
Step 4: SET PREPTR = PTR
Step 5: SET PTR = PTR -> NEXT
[END OF LOOP]
Step 6: SET PREPTR -> NEXT = HEAD
Step 7: FREE PTR
Step 8: EXIT
 Circular doubly linked list is a more complexed type of
data structure in which a node contain pointers to its
previous node as well as the next node.
 Circular doubly linked list doesn't contain NULL in any
of the node.
 The last node of the list contains the address of the first
node of the list.
 The first node of the list also contain address of the last
node in its previous pointer.
Algorithm
Step 1: IF PTR = NULL
Write OVERFLOW
Go to Step 13
[END OF IF]
Step 2: SET NEW_NODE = PTR
Step 3: SET PTR = PTR -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET TEMP = HEAD
Step 6: Repeat Step 7 while TEMP -> NEXT != HEAD
Step 7: SET TEMP = TEMP -> NEXT
[END OF LOOP]
Step 8: SET TEMP -> NEXT = NEW_NODE
Step 9: SET NEW_NODE -> PREV = TEMP
Step 1 : SET NEW_NODE -> NEXT = HEAD
Step 11: SET HEAD -> PREV = NEW_NODE
Step 12: SET HEAD = NEW_NODE
Step 13: EXIT
Algorithm
Step 1: IF HEAD = NULL
Write UNDERFLOW
Go to Step 8
[END OF IF]
Step 2: SET TEMP = HEAD
Step 3: Repeat Step 4 while TEMP -> NEXT != HEAD
Step 4: SET TEMP = TEMP -> NEXT
[END OF LOOP]
Step 5: SET TEMP -> PREV -> NEXT = HEAD
Step 6: SET HEAD -> PREV = TEMP -> PREV
Step 7: FREE TEMP
Step 8: EXIT
 A tree is also one of the data structures that represent
hierarchical data. Suppose we want to show the
employees and their positions in the hierarchical form
then it can be represented as shown below:
some key points of the Tree data structure.
 A tree data structure is defined as a collection of objects
or entities known as nodes that are linked together to
represent or simulate hierarchy.
 A tree data structure is a non-linear data structure
because it does not store in a sequential manner. It is a
hierarchical structure as elements in a Tree are arranged
in multiple levels.
 In the Tree data structure, the topmost node is known as
a root node. Each node contains some data, and data
can be of any type. In the above tree structure, the node
contains the name of the employee, so the type of data
would be a string.
 Each node contains some data and the link or reference
of other nodes that can be called children.
Path − Path refers to the sequence of nodes along the edges of a tree.
Root − The node at the top of the tree is called root. There is only one
root per tree and one path from the root node to any node.
Parent − Any node except the root node has one edge upward to a
node called parent.
Child − The node below a given node connected by its edge
downward is called its child node.
Leaf − The node which does not have any child node is called the leaf
node.
Subtree − Subtree represents the descendants of a node.
Visiting − Visiting refers to checking the value of a node when control
is on the node.
Traversing − Traversing means passing through nodes in a specific
order.
 Binary Tree is a special data structure used for data
storage purposes.
 A binary tree has a special condition that each node
can have a maximum of two children.
 Here, binary name itself suggests that 'two'; therefore,
each node can have either 0, 1 or 2 children.
The above tree is a binary tree because each node
contains the utmost two children. The logical
representation of the above tree is given below:
 Binary Search Tree is a node-based binary tree data
structure which has the following properties:
 The left subtree of a node contains only nodes with
keys lesser than the node’s key.
 The right subtree of a node contains only nodes with
keys greater than the node’s key.
 The left and right subtree each must also be a binary
search tree.
Representation
 BST is a collection of nodes arranged in a way where
they maintain BST properties.
 Each node has a key and an associated value.
 While searching, the desired key is compared to the
keys in BST and if found, the associated value is
retrieved.
 Following is a pictorial representation of BST
 We observe that the root node key (27) has all less-
valued keys on the left sub-tree and the higher valued
keys on the right sub-tree.
Basic Operations
Following are the basic operations of a tree −
 Search − Searches an element in a tree.
 Insert − Inserts an element in a tree.
 Pre-order Traversal − Traverses a tree in a pre-order
manner.
 In-order Traversal − Traverses a tree in an in-order
manner.
 Post-order Traversal − Traverses a tree in a post-order
manner.
Node
 Define a node having some data, references to its left
and right child nodes.
struct node
{ int data;
struct node *leftChild;
struct node *rightChild;
};
 The algorithm depends on the property of BST that if
each left subtree has values below root and each right
subtree has values above the root.
 If the value is below the root, we can say for sure that
the value is not in the right subtree; we need to only
search in the left subtree and if the value is above the
root, we can say for sure that the value is not in the left
subtree; we need to only search in the right subtree.
 Algorithm:
If root == NULL
return NULL;
If number == root->data
return root->data;
If number < root->data
return search(root->left)
If number > root->data
return search(root->right)
 Inserting a value in the correct position is similar to
searching because we try to maintain the rule that the
left subtree is lesser than root and the right subtree is
larger than root.
 We keep going to either right subtree or left subtree
depending on the value and when we reach a point left
or right subtree is null, we put the new node there.
 Algorithm:
If node == NULL
return createNode(data)
if (data < node->data)
node->left = insert(node->left, data);
else if (data > node->data)
node->right = insert(node->right, data);
return node;
Case I
 In the first case, the node to be deleted is the
leaf node. In such a case, simply delete the
node from the tree.
Case II
 In the second case, the node to be deleted lies has a
single child node. In such a case follow the steps
below:
 Replace that node with its child node.
 Remove the child node from its original position.
 A Heap is a special Tree-based data structure in which
the tree is a complete binary tree. Generally, Heaps can
be of two types:
 Max-Heap: In a Max-Heap the key present at the root
node must be greatest among the keys present at all of
it’s children. The same property must be recursively
true for all sub-trees in that Binary Tree.
 Min-Heap: In a Min-Heap the key present at the root
node must be minimum among the keys present at all
of it’s children. The same property must be recursively
true for all sub-trees in that Binary Tree.
 http://www.btechsmartclass.com/data_structures/tree-
terminology.html
Preorder Traversal-
100 , 20 , 10 , 30 , 200 , 150 , 300
Inorder Traversal-
10 , 20 , 30 , 100 , 150 , 200 , 300
Postorder Traversal-
10 , 30 , 20 , 150 , 300 , 200 , 100
 Tree is a non-linear data structure which organizes data
in a hierarchical structure and this is a recursive
definition.
OR
 A tree is a connected graph without any circuits.
OR
 If in a graph, there is one and only one path between
every pair of vertices, then graph is called as a tree.
Properties-
 The important properties of tree data structure are-
 There is one and only one path between every pair of
vertices in a tree.
 A tree with n vertices has exactly (n-1) edges.
 A graph is a tree if and only if it is minimally
connected.
 Any connected graph with n vertices and (n-1) edges is
a tree.
 Binary tree is a special tree data structure in
which each node can have at most 2 children.
 Thus, in a binary tree,
 Each node has either 0 child or 1 child or 2
children.
 A binary tree is unlabeled if its nodes are not assigned
any label.
 A binary tree is labeled if all its nodes are assigned a
label.
 Rooted Binary Tree
 Full / Strictly Binary Tree
 Complete / Perfect Binary Tree
 Almost Complete Binary Tree
 Skewed Binary Tree
Rooted Binary Tree
 A rooted binary tree is a binary tree that satisfies the
following 2 properties-
 It has a root node.
 Each node has at most 2 children.
Full / Strictly Binary Tree
 A binary tree in which every node has either 0 or 2
children is called as a Full binary tree.
 Full binary tree is also called as Strictly binary tree.
Here,
 First binary tree is not a full binary tree.
 This is because node C has only 1 child.
 A complete binary tree is a binary tree that satisfies
the following 2 properties-
 Every internal node has exactly 2 children.
 All the leaf nodes are at the same level.
 Complete binary tree is also called as Perfect binary
tree.
Here,
 First binary tree is not a complete binary tree.
 This is because all the leaf nodes are not at the same
level.
 An almost complete binary tree is a binary tree that
satisfies the following 2 properties-
 All the levels are completely filled except possibly the
last level.
 The last level must be strictly filled from left to right.
Here,
First binary tree is not an almost complete binary tree.
This is because the last level is not filled from left to right.
 A skewed binary tree is a binary tree that satisfies the
following 2 properties-
 All the nodes except one node has one and only one
child.
 The remaining node has no child.
OR
 A skewed binary tree is a binary tree of n nodes such
that its depth is (n-1).
Data structures
Data structures

Más contenido relacionado

La actualidad más candente

Stacks and queues
Stacks and queuesStacks and queues
Stacks and queues
Abbott
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queues
tech4us
 
Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structure,abstraction,abstract data type,static and dynamic,time and spa...Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Hassan Ahmed
 

La actualidad más candente (20)

Stacks and queues
Stacks and queuesStacks and queues
Stacks and queues
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its Fundamentals
 
Data Structure Using C
Data Structure Using CData Structure Using C
Data Structure Using C
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
 
DATA STRUCTURE IN C LANGUAGE
DATA STRUCTURE IN C LANGUAGEDATA STRUCTURE IN C LANGUAGE
DATA STRUCTURE IN C LANGUAGE
 
Datastructure
DatastructureDatastructure
Datastructure
 
Data Structure
Data StructureData Structure
Data Structure
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
 
Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive
 
Introduction to Data Structure : Pointer
Introduction to Data Structure : PointerIntroduction to Data Structure : Pointer
Introduction to Data Structure : Pointer
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 
Data structures using C
Data structures using CData structures using C
Data structures using C
 
Data Structure Basics
Data Structure BasicsData Structure Basics
Data Structure Basics
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
Fallsem2015 16 cp1699-20-jul-2015_rm01_stacks_and_queues
Fallsem2015 16 cp1699-20-jul-2015_rm01_stacks_and_queuesFallsem2015 16 cp1699-20-jul-2015_rm01_stacks_and_queues
Fallsem2015 16 cp1699-20-jul-2015_rm01_stacks_and_queues
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queues
 
Introduction to Data Structure
Introduction to Data Structure Introduction to Data Structure
Introduction to Data Structure
 
Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structure,abstraction,abstract data type,static and dynamic,time and spa...Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structure,abstraction,abstract data type,static and dynamic,time and spa...
 
Ii pu cs practical viva voce questions
Ii pu cs  practical viva voce questionsIi pu cs  practical viva voce questions
Ii pu cs practical viva voce questions
 

Similar a Data structures

queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
RAtna29
 
Data Structures in C
Data Structures in CData Structures in C
Data Structures in C
Jabs6
 

Similar a Data structures (20)

DSA Lab Manual C Scheme.pdf
DSA Lab Manual C Scheme.pdfDSA Lab Manual C Scheme.pdf
DSA Lab Manual C Scheme.pdf
 
01-Introduction of DSA-1.pptx
01-Introduction of DSA-1.pptx01-Introduction of DSA-1.pptx
01-Introduction of DSA-1.pptx
 
TSAT Presentation1.pptx
TSAT Presentation1.pptxTSAT Presentation1.pptx
TSAT Presentation1.pptx
 
chapter three ppt.pptx
chapter three ppt.pptxchapter three ppt.pptx
chapter three ppt.pptx
 
Unit i(dsc++)
Unit i(dsc++)Unit i(dsc++)
Unit i(dsc++)
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddu
 
unit 5 stack & queue.ppt
unit 5 stack & queue.pptunit 5 stack & queue.ppt
unit 5 stack & queue.ppt
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
chapter-4-data-structure.pdf
chapter-4-data-structure.pdfchapter-4-data-structure.pdf
chapter-4-data-structure.pdf
 
1.1 ADS data-structure.pdf
1.1 ADS data-structure.pdf1.1 ADS data-structure.pdf
1.1 ADS data-structure.pdf
 
Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1
 
DS UNIT2QUEUES.pptx
DS UNIT2QUEUES.pptxDS UNIT2QUEUES.pptx
DS UNIT2QUEUES.pptx
 
Data Structure
Data Structure Data Structure
Data Structure
 
Data Structures and algoithms Unit - 1.pptx
Data Structures and algoithms Unit - 1.pptxData Structures and algoithms Unit - 1.pptx
Data Structures and algoithms Unit - 1.pptx
 
basics of queues
basics of queuesbasics of queues
basics of queues
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Data structure
Data structureData structure
Data structure
 
Data structure.ppt
Data structure.pptData structure.ppt
Data structure.ppt
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
Data Structures in C
Data Structures in CData Structures in C
Data Structures in C
 

Último

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Último (20)

SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 

Data structures

  • 1. Dr.C.Naveeth Babu Department of CS Kristu Jayanti College, Bangalore
  • 2. A Queue is a linear structure which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added.
  • 3.
  • 4. A real-world example of queue can be a single-lane one-way road, where the vehicle enters first, exits first. More real-world examples can be seen as queues at the ticket windows and bus-stops.
  • 5. Basic Operations enqueue() − add (store) an item to the queue. dequeue() − remove (access) an item from the queue.
  • 6.  Queues maintain two data pointers, front and rear. Therefore, its operations are comparatively difficult to implement than that of stacks.  The following steps should be taken to enqueue (insert) data into a queue −  Step 1 − Check if the queue is full.  Step 2 − If the queue is full, produce overflow error and exit.  Step 3 − If the queue is not full, increment rear pointer to point the next empty space.  Step 4 − Add data element to the queue location, where the rear is pointing.  Step 5 − return success.
  • 7.
  • 8. procedure enqueue(data) if queue is full return overflow endif rear ← rear + 1 queue[rear] ← data return true end procedure
  • 9. int enqueue(int data) if(isfull()) return 0; rear = rear + 1; queue[rear] = data; return 1; end procedure
  • 10.  Accessing data from the queue is a process of two tasks − access the data where front is pointing and remove the data after access. The following steps are taken to perform dequeue operation −  Step 1 − Check if the queue is empty.  Step 2 − If the queue is empty, produce underflow error and exit.  Step 3 − If the queue is not empty, access the data where front is pointing.  Step 4 − Increment front pointer to point to the next available data element.  Step 5 − Return success.
  • 11.
  • 12. procedure dequeue if queue is empty return underflow end if data = queue[front] front ← front + 1 return true end procedure
  • 13. int dequeue() { if(isempty()) return 0; int data = queue[front]; front = front + 1; return data; }
  • 14. We can easily represent queue by using linear arrays. There are two variables i.e. front and rear, that are implemented in the case of every queue. Front and rear variables point to the position from where insertions and deletions are performed in a queue. Initially, the value of front and queue is -1 which represents an empty queue. Array representation of a queue containing 5 elements along with the respective values of front and rear, is shown in the following figure.
  • 15.
  • 16.
  • 17.
  • 18.  A simple queue is the most basic queue. In this queue, the enqueue operation takes place at the rear, while the dequeue operation takes place at the front:
  • 19.  Its applications are process scheduling, disk scheduling, memory management, IO buffer, pipes, call center phone systems, and interrupt handling.
  • 20.  Circular Queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called ‘Ring Buffer’.
  • 21.  In a circular queue, all nodes are treated as circular. Last node is connected back to the first node.  Circular queue is also called as Ring Buffer.  It is an abstract data type.  Circular queue contains a collection of data which allows insertion of data at the end of the queue and deletion of data at the beginning of the queue.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.  A deque, also known as a double-ended queue, is an ordered collection of items similar to the queue. It has two ends, a front and a rear, and the items remain positioned in the collection.  What makes a deque different is the unrestrictive nature of adding and removing items. New items can be added at either the front or the rear. Likewise, existing items can be removed from either end.
  • 28.
  • 29.  The deque abstract data type is defined by the following structure and operations.  A deque is structured, as described above, as an ordered collection of items where items are added and removed from either end, either front or rear.  The deque operations are given below.
  • 30.  Deque() creates a new deque that is empty. It needs no parameters and returns an empty deque.  add_front(item) adds a new item to the front of the deque. It needs the item and returns nothing.  add_rear(item) adds a new item to the rear of the deque. It needs the item and returns nothing.  remove_front() removes the front item from the deque. It needs no parameters and returns the item. The deque is modified.  remove_rear() removes the rear item from the deque. It needs no parameters and returns the item. The deque is modified.  is_empty() tests to see whether the deque is empty. It needs no parameters and returns a boolean value.  size() returns the number of items in the deque. It needs no parameters and returns an integer.
  • 31. Deque Operation Deque Contents d.is_empty() [] d.add_rear(4) [4] d.add_rear('dog') ['dog', 4] d.add_front('cat') ['dog', 4, 'cat'] d.add_front(True) ['dog', 4,'cat', True] d.size() ['dog', 4, 'cat', True] d.is_empty() ['dog', 4, 'cat', True] d.add_rear(8.4) [8.4, 'dog', 4, 'cat',True] d.remove_rear() ['dog', 4, 'cat', True] d.remove_front() `['dog', 4, 'cat']
  • 32.  A priority queue is a special type of queue in which each element is associated with a priority and is served according to its priority.  Generally, the value of the element itself is considered for assigning the priority.  For example, The element with the highest value is considered as the highest priority element.
  • 33.  Job Scheduling on a shared computer  Event – driven simulation
  • 34. Basic Operations  insert / enqueue − add an item to the rear of the queue.  remove / dequeue − remove an item from the front of the queue.
  • 35.
  • 36. There is few more operations supported by queue which are following.  Peek − get the element at front of the queue.  isFull − check if queue is full.  isEmpty − check if queue is empty.
  • 37.  Whenever an element is inserted into queue, priority queue inserts the item according to its order. Here we're assuming that data with high value has low priority.
  • 38.
  • 39.  A data structure is a particular way of organizing data in a computer so that it can be used effectively.  For example, we can store a list of items having the same data-type using the array data structure.
  • 40. There are two types of data structures:  Primitive data structure  Non-primitive data structure Primitive Data structure  The primitive data structures are primitive data types. The int, char, float, double, and pointer are the primitive data structures that can hold a single value. Non-Primitive Data structure The non-primitive data structure is divided into two types:  Linear data structure  Non-linear data structure
  • 41. Linear Data Structure  The arrangement of data in a sequential manner is known as a linear data structure. The data structures used for this purpose are Arrays, Linked list, Stacks, and Queues. In these data structures, one element is connected to only one another element in a linear form. Non Linear Data Structure  When one element is connected to the 'n' number of elements known as a non-linear data structure. The best example is trees and graphs. In this case, the elements are arranged in a random manner.
  • 42. Data structures can also be classified as:  Static data structure: It is a type of data structure where the size is allocated at the compile time. Therefore, the maximum size is fixed.  Dynamic data structure: It is a type of data structure where the size is allocated at the run time. Therefore, the maximum size is flexible.
  • 43. The major or the common operations that can be performed on the data structures are:  Searching: We can search for any element in a data structure.  Sorting: We can sort the elements of a data structure either in an ascending or descending order.  Insertion: We can also insert the new element in a data structure.  Updation: We can also update the element, i.e., we can replace the element with another element.  Deletion: We can also perform the delete operation to remove the element from the data structure.
  • 44. The pointer in C language is a variable which stores the address of another variable. Consider the following example to define a pointer which stores the address of an integer. int n = 10; int*p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
  • 45.  The pointer in c language can be declared using * (asterisk symbol). Syntax data_type * pointer_variable_name; Example int *a;//pointer to int char *c;//pointer to char
  • 46. int *ptr_thing; /* pointer to an integer */ int *ptr1,thing;/* ptr1 is a pointer to type integer and thing is an integer variable */ double *ptr2; /* pointer to a double */ float *ptr3; /* pointer to a float */ char *ch1 ; /* pointer to a character */ float *ptr, variable;/*ptr is a pointer to type float and variable is an ordinary float variable */
  • 47. Operator Meaning * Serves 2 purpose 1.Declaration of a pointer 2.Returns the value of the referenced variable & Serves only 1 purpose - Returns the address of a variable
  • 48.
  • 49.  Static Memory is allocated for declared variables by the compiler.  Static memory allocation is an allocation technique which allocates a fixed amount of memory during compile time and the operating system internally uses a data structure known as Stack to manage this.  The memory is allocated during compile time.
  • 50.  Variables get allocated permanently  Allocation is done before program execution  It uses the data structure called stack for implementing static allocation  Less efficient  There is no memory reusability
  • 51. All the variables in the program below are statically allocated. void play { int a; } int main() { int b; int c[10]; } In this type of allocation, you strictly allocate memory for your data at compile time.
  • 52.  Simplicity of usage.  Efficient execution time.  Need not worry about memory allocation/re- allocation/freeing of memory  Variables remain permanently allocated.
  • 53.  Main disadvantage is wastage of memory.  Memory can't be freed when it is no longer needed.
  • 54.  Memory allocation done at the time of execution(run time) is known as dynamic memory allocation.  Functions calloc() and malloc() support allocating dynamic memory.
  • 55.  Data structures can grow and shrink according to the requirement. ◦ We can allocate (create) additional storage whenever we need them. ◦ We can de-allocate (free/delete) dynamic space whenever we are done with them.  Dynamic Allocation is done at run time.
  • 56.  As the memory is allocated during runtime, it requires more time.  Memory needs to be freed by the user when done. This is important as it is more likely to turn into bugs that are difficult to find.
  • 57. S.No Static Memory Allocation Dynamic Memory Allocation 1 In the static memory allocation, variables get allocated permanently. In the Dynamic memory allocation, variables get allocated only if your program unit gets active. 2 Static Memory Allocation is done before program execution. Dynamic Memory Allocation is done during program execution. 3 It uses stack for managing the static allocation of memory It uses heap for managing the dynamic allocation of memory 4 It is less efficient It is more efficient 5 In Static Memory Allocation, there is no memory re-usability In Dynamic Memory Allocation, there is memory re-usability and memory can be freed when not required 6 In static memory allocation, once the memory is allocated, the memory size can not change. In dynamic memory allocation, when memory is allocated the memory size can be changed.
  • 58. 7 In this memory is allocated at compile time. In this memory is allocated at run time. 8 In this allocated memory remains from start to end of the program. In this allocated memory can be released at any time during the program. 9 Example: This static memory allocation is generally used for array. Example: This dynamic memory allocation is generally used for linked list.
  • 59. malloc() - The name "malloc" stands for memory allocation. The malloc() function reserves a block of memory of the specified number of bytes.
  • 60. Syntax of malloc() ptr = (castType*) malloc(size); Example ptr = (float*) malloc (100 * sizeof(float)); The above statement allocates 400 bytes of memory. It's because the size of float is 4 bytes. And, the pointer ptr holds the address of the first byte in the allocated memory.
  • 61.  Calloc - The name "calloc" stands for contiguous allocation.  The malloc() function allocates memory and leaves the memory uninitialized, whereas the calloc() function allocates memory and initializes all bits to zero.
  • 62. Syntax of calloc()  ptr = (castType*)calloc(n, size); Example:  ptr = (float*) calloc(25, sizeof(float)); The above statement allocates contiguous space in memory for 25 elements of type float.
  • 63.  realloc() - the dynamically allocated memory is insufficient or more than required, you can change the size of previously allocated memory using the realloc() function. Syntax of realloc() ptr = realloc(ptr, x); Here, ptr is reallocated with a new size x.
  • 64.  A linked list is a sequence of data structures, which are connected together via links.  Linked List is a sequence of links which contains items.  Each link contains a connection to another link.  Linked list is the second most-used data structure after array.
  • 65.  Linked List contains a link element called first or head.  Each link carries a data field(s) and a link field called next.  Each link is linked with its next link using its next link.  Last link carries a link as null to mark the end of the list.
  • 66.
  • 67. Following are the various types of linked list.  Simple Linked List − Item navigation is forward only.  Doubly Linked List − Items can be navigated forward and backward.  Circular Linked List − Last item contains link of the first element as next and the first element has a link to the last element as previous.
  • 68. Following are the basic operations supported by a list.  Insertion − Adds an element at the beginning of the list.  Deletion − Deletes an element at the beginning of the list.  Display − Displays the complete list.  Search − Searches an element using the given key.  Delete − Deletes an element using the given key.
  • 69. Dynamic Data Structure  Linked list is a dynamic data structure so it can grow and shrink at runtime by allocating and deallocating memeory. So there is no need to give initial size of linked list. Insertion and Deletion  Insertion and deletion of nodes are really easier.
  • 70. No Memory Wastage  As size of linked list can increase or decrease at run time so there is no memory wastage. Implementation  Data structures such as stack and queues can be easily implemented using linked list.
  • 71. Memory Usage  More memory is required to store elements in linked list as compared to array. Because in linked list each node contains a pointer and it requires extra memory for itself. Traversal  Elements or nodes traversal is difficult in linked list. We can not randomly access any element as we do in array by index. For example if we want to access a node at position n then we have to traverse all the nodes before it. So, time required to access a node is large.
  • 72. Reverse traversing  Reverse traversing in a linked list is very difficult, because it requires more memory for the pointer.
  • 73.  It is used to maintain directory names.  The linked list can perform arithmetic operations in the long integer.  We can also use it to next and previous images in the image viewer.  With the help of the linked list, we can move songs back and forth in the music player.  The linked list is also used for undo in word and Photoshop applications.
  • 74. Insertion Operation Adding a new node in linked list is a more than one step activity. We shall learn this with diagrams here. First, create a node using the same structure and find the location where it has to be inserted. Imagine that we are inserting a node B (NewNode), between A (LeftNode) and C (RightNode).
  • 75. NewNode.next −> RightNode; Now, the next node at the left should point to the new node.
  • 76. LeftNode.next −> NewNode; This will put the new node in the middle of the two. The new list should look like this −
  • 77.
  • 78. /* inserts a new node on the front of the list. */ void push(struct Node** head_ref, int new_data) { /* 1. allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* 2. put in the data */ new_node->data = new_data; /* 3. Make next of new node as head */ new_node->next = (*head_ref); /* 4. move the head to point to the new node */ (*head_ref) = new_node; }
  • 79.  Deletion Operation Deletion is also a more than one step process. We shall learn with pictorial representation. First, locate the target node to be removed, by using searching algorithms.
  • 80.  The left (previous) node of the target node now should point to the next node of the target node − LeftNode.next −> TargetNode.next;  This will remove the link that was pointing to the target node. Now, using the following code, we will remove what the target node is pointing at.
  • 81.  This will remove the link that was pointing to the target node. Now, using the following code, we will remove what the target node is pointing at. TargetNode.next −> NULL;
  • 82.  Doubly linked list is a type of linked list in which each node apart from storing its data has two links.  The first link points to the previous node in the list and the second link points to the next node in the list.  The first node of the list has its previous link pointing to NULL similarly the last node of the list has its next node pointing to NULL.
  • 83.
  • 84.  Implementation of Doubly Linked List First we define the node. struct node { int data; // Data node *prev; // A reference to the previous node node *next; // A reference to the next node };
  • 85. Now we define our class Doubly Linked List. It has the following methods:  add_front: Adds a new node in the beginning of list  add_after: Adds a new node after another node  add_before: Adds a new node before another node  add_end: Adds a new node in the end of list  delete: Removes the node  forward_traverse: Traverse the list in forward direction  backward_traverse: Traverse the list in backward direction
  • 86.
  • 87.  A doubly linked list containing three nodes having numbers from 1 to 3 in their data part, is shown in the following image.
  • 88.  Insertion in doubly linked list at beginning Algorithm : Step 1: IF ptr = NULL Write OVERFLOW Go to Step 9 [END OF IF] Step 2: SET NEW_NODE = ptr Step 3: SET ptr = ptr -> NEXT Step 4: SET NEW_NODE -> DATA = VAL Step 5: SET NEW_NODE -> PREV = NULL Step 6: SET NEW_NODE -> NEXT = START Step 7: SET head -> PREV = NEW_NODE Step 8: SET head = NEW_NODE Step 9: EXIT
  • 89.
  • 90.  Deletion in doubly linked list at the end Step 1: IF HEAD = NULL Write UNDERFLOW Go to Step 7 [END OF IF] Step 2: SET TEMP = HEAD Step 3: REPEAT STEP 4 WHILE TEMP->NEXT != NULL Step 4: SET TEMP = TEMP->NEXT [END OF LOOP] Step 5: SET TEMP ->PREV-> NEXT = NULL Step 6: FREE TEMP Step 7: EXIT
  • 91.
  • 92.  A circular linked list is a sequence of elements in which every element has a link to its next element in the sequence and the last element has a link to the first element.
  • 93. Operations In a circular linked list, we perform the following operations...  Insertion  Deletion  Display
  • 94.
  • 95. Step 1: IF PTR = NULL Write OVERFLOW Go to Step 11 [END OF IF] Step 2: SET NEW_NODE = PTR Step 3: SET PTR = PTR -> NEXT Step 4: SET NEW_NODE -> DATA = VAL Step 5: SET TEMP = HEAD Step 6: Repeat Step 8 while TEMP -> NEXT != HEAD Step 7: SET TEMP = TEMP -> NEXT [END OF LOOP] Step 8: SET NEW_NODE -> NEXT = HEAD Step 9: SET TEMP → NEXT = NEW_NODE Step 10: SET HEAD = NEW_NODE Step 11: EXIT
  • 96.
  • 97.  Deletion in Circular singly linked list at the end Algorithm Step 1: IF HEAD = NULL Write UNDERFLOW Go to Step 8 [END OF IF] Step 2: SET PTR = HEAD Step 3: Repeat Steps 4 and 5 while PTR -> NEXT != HEAD Step 4: SET PREPTR = PTR Step 5: SET PTR = PTR -> NEXT [END OF LOOP] Step 6: SET PREPTR -> NEXT = HEAD Step 7: FREE PTR Step 8: EXIT
  • 98.
  • 99.  Circular doubly linked list is a more complexed type of data structure in which a node contain pointers to its previous node as well as the next node.  Circular doubly linked list doesn't contain NULL in any of the node.  The last node of the list contains the address of the first node of the list.  The first node of the list also contain address of the last node in its previous pointer.
  • 100.
  • 101.
  • 102. Algorithm Step 1: IF PTR = NULL Write OVERFLOW Go to Step 13 [END OF IF] Step 2: SET NEW_NODE = PTR Step 3: SET PTR = PTR -> NEXT Step 4: SET NEW_NODE -> DATA = VAL Step 5: SET TEMP = HEAD Step 6: Repeat Step 7 while TEMP -> NEXT != HEAD Step 7: SET TEMP = TEMP -> NEXT [END OF LOOP] Step 8: SET TEMP -> NEXT = NEW_NODE Step 9: SET NEW_NODE -> PREV = TEMP Step 1 : SET NEW_NODE -> NEXT = HEAD Step 11: SET HEAD -> PREV = NEW_NODE Step 12: SET HEAD = NEW_NODE Step 13: EXIT
  • 103.
  • 104. Algorithm Step 1: IF HEAD = NULL Write UNDERFLOW Go to Step 8 [END OF IF] Step 2: SET TEMP = HEAD Step 3: Repeat Step 4 while TEMP -> NEXT != HEAD Step 4: SET TEMP = TEMP -> NEXT [END OF LOOP] Step 5: SET TEMP -> PREV -> NEXT = HEAD Step 6: SET HEAD -> PREV = TEMP -> PREV Step 7: FREE TEMP Step 8: EXIT
  • 105.
  • 106.  A tree is also one of the data structures that represent hierarchical data. Suppose we want to show the employees and their positions in the hierarchical form then it can be represented as shown below:
  • 107. some key points of the Tree data structure.  A tree data structure is defined as a collection of objects or entities known as nodes that are linked together to represent or simulate hierarchy.  A tree data structure is a non-linear data structure because it does not store in a sequential manner. It is a hierarchical structure as elements in a Tree are arranged in multiple levels.
  • 108.  In the Tree data structure, the topmost node is known as a root node. Each node contains some data, and data can be of any type. In the above tree structure, the node contains the name of the employee, so the type of data would be a string.  Each node contains some data and the link or reference of other nodes that can be called children.
  • 109.
  • 110. Path − Path refers to the sequence of nodes along the edges of a tree. Root − The node at the top of the tree is called root. There is only one root per tree and one path from the root node to any node. Parent − Any node except the root node has one edge upward to a node called parent. Child − The node below a given node connected by its edge downward is called its child node. Leaf − The node which does not have any child node is called the leaf node. Subtree − Subtree represents the descendants of a node. Visiting − Visiting refers to checking the value of a node when control is on the node. Traversing − Traversing means passing through nodes in a specific order.
  • 111.  Binary Tree is a special data structure used for data storage purposes.  A binary tree has a special condition that each node can have a maximum of two children.  Here, binary name itself suggests that 'two'; therefore, each node can have either 0, 1 or 2 children.
  • 112.
  • 113. The above tree is a binary tree because each node contains the utmost two children. The logical representation of the above tree is given below:
  • 114.  Binary Search Tree is a node-based binary tree data structure which has the following properties:  The left subtree of a node contains only nodes with keys lesser than the node’s key.  The right subtree of a node contains only nodes with keys greater than the node’s key.  The left and right subtree each must also be a binary search tree.
  • 115.
  • 116. Representation  BST is a collection of nodes arranged in a way where they maintain BST properties.  Each node has a key and an associated value.  While searching, the desired key is compared to the keys in BST and if found, the associated value is retrieved.
  • 117.  Following is a pictorial representation of BST  We observe that the root node key (27) has all less- valued keys on the left sub-tree and the higher valued keys on the right sub-tree.
  • 118. Basic Operations Following are the basic operations of a tree −  Search − Searches an element in a tree.  Insert − Inserts an element in a tree.  Pre-order Traversal − Traverses a tree in a pre-order manner.  In-order Traversal − Traverses a tree in an in-order manner.  Post-order Traversal − Traverses a tree in a post-order manner.
  • 119. Node  Define a node having some data, references to its left and right child nodes. struct node { int data; struct node *leftChild; struct node *rightChild; };
  • 120.  The algorithm depends on the property of BST that if each left subtree has values below root and each right subtree has values above the root.  If the value is below the root, we can say for sure that the value is not in the right subtree; we need to only search in the left subtree and if the value is above the root, we can say for sure that the value is not in the left subtree; we need to only search in the right subtree.
  • 121.  Algorithm: If root == NULL return NULL; If number == root->data return root->data; If number < root->data return search(root->left) If number > root->data return search(root->right)
  • 122.  Inserting a value in the correct position is similar to searching because we try to maintain the rule that the left subtree is lesser than root and the right subtree is larger than root.  We keep going to either right subtree or left subtree depending on the value and when we reach a point left or right subtree is null, we put the new node there.
  • 123.  Algorithm: If node == NULL return createNode(data) if (data < node->data) node->left = insert(node->left, data); else if (data > node->data) node->right = insert(node->right, data); return node;
  • 124. Case I  In the first case, the node to be deleted is the leaf node. In such a case, simply delete the node from the tree.
  • 125.
  • 126. Case II  In the second case, the node to be deleted lies has a single child node. In such a case follow the steps below:  Replace that node with its child node.  Remove the child node from its original position.
  • 127.
  • 128.
  • 129.
  • 130.  A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Generally, Heaps can be of two types:  Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree.  Min-Heap: In a Min-Heap the key present at the root node must be minimum among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree.
  • 131.
  • 133.
  • 134.
  • 135. Preorder Traversal- 100 , 20 , 10 , 30 , 200 , 150 , 300 Inorder Traversal- 10 , 20 , 30 , 100 , 150 , 200 , 300 Postorder Traversal- 10 , 30 , 20 , 150 , 300 , 200 , 100
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.  Tree is a non-linear data structure which organizes data in a hierarchical structure and this is a recursive definition. OR  A tree is a connected graph without any circuits. OR  If in a graph, there is one and only one path between every pair of vertices, then graph is called as a tree.
  • 150.
  • 151. Properties-  The important properties of tree data structure are-  There is one and only one path between every pair of vertices in a tree.  A tree with n vertices has exactly (n-1) edges.  A graph is a tree if and only if it is minimally connected.  Any connected graph with n vertices and (n-1) edges is a tree.
  • 152.  Binary tree is a special tree data structure in which each node can have at most 2 children.  Thus, in a binary tree,  Each node has either 0 child or 1 child or 2 children.
  • 153.
  • 154.  A binary tree is unlabeled if its nodes are not assigned any label.
  • 155.  A binary tree is labeled if all its nodes are assigned a label.
  • 156.  Rooted Binary Tree  Full / Strictly Binary Tree  Complete / Perfect Binary Tree  Almost Complete Binary Tree  Skewed Binary Tree
  • 157. Rooted Binary Tree  A rooted binary tree is a binary tree that satisfies the following 2 properties-  It has a root node.  Each node has at most 2 children.
  • 158. Full / Strictly Binary Tree  A binary tree in which every node has either 0 or 2 children is called as a Full binary tree.  Full binary tree is also called as Strictly binary tree.
  • 159. Here,  First binary tree is not a full binary tree.  This is because node C has only 1 child.
  • 160.  A complete binary tree is a binary tree that satisfies the following 2 properties-  Every internal node has exactly 2 children.  All the leaf nodes are at the same level.  Complete binary tree is also called as Perfect binary tree.
  • 161. Here,  First binary tree is not a complete binary tree.  This is because all the leaf nodes are not at the same level.
  • 162.  An almost complete binary tree is a binary tree that satisfies the following 2 properties-  All the levels are completely filled except possibly the last level.  The last level must be strictly filled from left to right.
  • 163. Here, First binary tree is not an almost complete binary tree. This is because the last level is not filled from left to right.
  • 164.  A skewed binary tree is a binary tree that satisfies the following 2 properties-  All the nodes except one node has one and only one child.  The remaining node has no child. OR  A skewed binary tree is a binary tree of n nodes such that its depth is (n-1).