Dsa Module 3
Dsa Module 3
FIRST
FIRST
Program code for reverse operation
struct Node* reverseLinkedList(struct Node* head)
{
struct Node* prev = NULL;
struct Node* current = head;
struct Node* nextNode = NULL;
Page 1
DATA STRUCTURES AND APPLICATIONS (BCS304)
FIRST2
Let us assume that the two linked lists are referenced by first1 and first2 respectively.
1. If the first linked list is empty then return first2.
2. If the second linked list is empty then return first1.
3. Store the address of the starting node of the first linked list in a pointer variable,
say temp.
4. Move the temp tothe last node of the linked list through simple linked list traversal
technique.
5. Store the address of the first node of the second linkedlist in the link field of the node
pointed by temp. Return first1.
Page 2
DATA STRUCTURES AND APPLICATIONS (BCS304)
List is unsorted
To do the search operation in the unsorted list, we need to follow the following steps:
1. Set first as t
2. Repeat step 3 while t≠NULL
3. If key = tdata; search is successful and return
Else set t=tlink
4. Search failed
5. Exit
Program code for Searching a key in an Unsorted Linked List
void search()
{ struct node *temp;
int key;
temp=first;
printf(“Enter key”);
scanf(“%d”, &key);
while (temp!=NULL)
{ if(key==tempdata)
{ printf(“Search successful”);
Page 3
DATA STRUCTURES AND APPLICATIONS (BCS304)
return;
}
else temp=templink;
}
printf(“Search failed”);
List is sorted
If we want to search any key element then we need to follow the step to do the search
operation for the sorted list, we need to follow the following steps:
1. Set temp=first
2. Repeat step 3 while temp≠NULL
3. If key>tempdata then set temp=templink
Else if key= tempdata then display search is success
Else display search is failed
4. Exit
Program code for Searching a key in a Sorted Linked List
void search()
{ struct node *temp;
int key;
temp=first;
printf(“Enter key”);
scanf(“%d”, &key);
while (temp!=NULL)
{ if (key>tempdata)
temp=templink;
else if(key==tempdata)
{ printf(“Search successful”);
return;
}
else
printf(“Search unsuccessful”);
}
printf(“Search unsuccessful”);
}
Page 4
DATA STRUCTURES AND APPLICATIONS (BCS304)
while(temp1->data != node_data)
{
if(temp1 -> link == NULL) {
printf("\nGiven node not found in the list!!!");
}
temp2 = temp1;
temp1 = temp1 ->link;
}
temp2 -> link= temp1 -> link;
free(temp1);
printf("\nOne node deleted!!!\n\n");
}
Page 6
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 7
DATA STRUCTURES AND APPLICATIONS (BCS304)
free(temp);
}
else
{
struct node*temp2=head;
while(temp->next!=head)
{
temp=temp->next;
}
head = head -> next;
temp->next=head;
free(temp2);
}
printf("\nDeletion success!!!");
}
}
Page 10
DATA STRUCTURES AND APPLICATIONS (BCS304)
In this representation, H0, H1..., H5 indicates the header nodes which are used to
represent indexes.
Remaining nodes are used to represent non-zero elements in the matrix, except the
very first node which is used to represent abstract information of the
sparse matrix (i.e., It is a matrix of 5 X 6 with 6 non-zero elements).
In this representation, in each row and column, the last node right field points to its
respective header node (Fig 3.2 (b)).
Page 11
DATA STRUCTURES AND APPLICATIONS (BCS304)
}
else
{
temp = HEAD;
while (temp -> next != NULL)
{
temp = temp -> next;
}
temp->next = ptr;
ptr->next = NULL;
}
}
}
void print()
{
struct list *tmp = HEAD;
printf("ROW NO COLUMN NO. VALUE \n");
while (tmp != NULL)
{
printf("%d \t\t %d \t\t %d \n", tmp->row, tmp->column, tmp->value);
tmp = tmp->next;
}
}
Page 13
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 14
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 15
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 16
DATA STRUCTURES AND APPLICATIONS (BCS304)
{
printf(“enter the details of the node %d”,i++);
temp = (NODE)malloc(sizeof (struct node));
printf("Enter the data to be inserted:\n");
scanf("%d",temp->data);
temp->prev = temp->next = NULL;
if (FIRST==NULL)
FIRST = END = temp;
else
{ END->next=temp;
temp->prev=END;
END=temp;
}
}
}
3.4.2.Insert to end
It works same as create function, by inserting new node to front. Here only one node can
be inserted at a time.
Program code for insert front operation
voidinsertend()
{ struct node * temp;
Page 17
DATA STRUCTURES AND APPLICATIONS (BCS304)
3.4.3.Insert to front
Here we start from first position. If nothing is there in the list, then ‘first’ is pointing to
NULL. So if first is NULL then the new node created itself will be pointing to last and
first. Then we create a new node temp usingmalloc and insert a new value=30 to it and
make its left and right link as NULL as in Fig. 3. If first is not equal to NULL, then
connect this temp to the left link of last node as in Fig.3.
Fig.3: Steps to Inserting a new Node to the front of Doubly Linked List
Page 18
DATA STRUCTURES AND APPLICATIONS (BCS304)
{ temp->next=FIRST;
FIRST->prev=temp;
FIRST=temp;
}
}
Page 20
DATA STRUCTURES AND APPLICATIONS (BCS304)
Fig.5: Steps to Deleting a Node from the end of a Doubly Linked List
Page 21
DATA STRUCTURES AND APPLICATIONS (BCS304)
END->next=NULL;
free(temp);
}
return ;
} // end of deletion end
Page 22
DATA STRUCTURES AND APPLICATIONS (BCS304)
3.4.6.Traverse (Display)
If first is pointing to NULL, then print that the list is empty. Else, make temp to point to first and
display tempdata. Then make temp to point to next node and display its data and so on until temp
points to NULL. So we traverse from first node to last node.
voiddisplay_count() //Display the status of DLL and count the number of nodes in it
{
temp=FIRST;
int count=0;
Page 23
DATA STRUCTURES AND APPLICATIONS (BCS304)
{
count++;
printf(“%d”,temp->data);
temp=temp->next;
}
printf("\n node count is %d\n",count);
} // end of else
return;
} // end of display()
Page 24
DATA STRUCTURES AND APPLICATIONS (BCS304)
A doubly linked list points to not only the next node but to the previous node as well. A circular
doubly linked list contains 2 NULL pointers. The ‘Next’ of the last node points to the first node in
a doubly-linked list. The ‘Prev’ of the first node points to the last node.
A doubly circular linked list looks as follows:
In this section, we will see how a new node is added into an already existing circular doubly linked
list. We will take two cases and then see how insertion is done in each case. Rest of the cases are
similar to that given for doubly linked lists.
Page 25
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 26
DATA STRUCTURES AND APPLICATIONS (BCS304)
In this section, we will see how a node is deleted from an already existing circular doubly linked list.
We will take two cases and then see how deletion is done in each case. Rest of the cases are same as
that given for doubly linked lists.
3.6.2.1. Deleting the First Node from a Circular Doubly Linked List:-
3.6.2.2. Deleting the Last Node from a Circular Doubly Linked List :-
Page 27
DATA STRUCTURES AND APPLICATIONS (BCS304)
1 *******************
2 Programming Example
*******************
3 1. Write a program to create a circular doubly linked list and perform
4 insertions and deletions at the beginning and end of the list.
5
6 #include <stdio.h>
7 #include <conio.h>
8 #include <malloc.h>
9
structnode
10 {
11 structnode *next;
12 intdata;
13 structnode *prev;
};
14
15
structnode *start = NULL;
16 structnode *create_ll(structnode *);
17 structnode *display(structnode *);
18 structnode *insert_beg(structnode *);
19 structnode *insert_end(structnode *);
structnode *delete_beg(structnode *);
20 structnode *delete_end(structnode *);
21 structnode *delete_node(structnode *);
22 structnode *delete_list(structnode *);
23
24 intmain()
25 {
intoption;
26 clrscr();
27 do
28 {
29 printf("\n\n *****MAIN MENU *****");
printf("\n 1: Create a list");
30 printf("\n 2: Display the list");
31 printf("\n 3: Add a node at the beginning");
32 printf("\n 4: Add a node at the end");
33 printf("\n 5: Delete a node from the beginning");
Page 28
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 29
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 30
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 31
DATA STRUCTURES AND APPLICATIONS (BCS304)
In linear data structure data is organized in sequential order and in non-linear data structure data is
organized in random order. A tree is a very popular non-linear data structure used in a wide range of
applications.In tree data structure, every individual element is called as Node. Node in a tree data
structure stores the actual data of that particular element and link to next element in hierarchical
structure.
3.7.Tree Definition
Definition: A tree is a finite set of one or more nodes such that: (i) there is a specially designated node
called the root; (ii) the remaining nodes are partitioned into n>= 0 disjoint sets T1, ...,Tn where each of
these sets is a tree. T1, ...,Tn are called the sub-trees of the root.
In a tree data structure, if we have N number of nodes then we can have a maximum of N-1 number of
links.
Page 32
DATA STRUCTURES AND APPLICATIONS (BCS304)
3.8.Basic Terminology
Root node: The root node R is the topmost node in the tree. If R = NULL, then it means the tree is
empty. Ex: A is the root node.
In a tree data structure, the first node is called as Root Node. Every tree must have a root node. We
can say that the root node is the origin of the tree data structure. In any tree, there must be only one
root node. We never have multiple root nodes in a tree.
Edge:In a tree data structure, the connecting link between any two nodes is called as EDGE. In a
tree with 'N' number of nodes there will be a maximum of 'N-1' number of edges.
Page 33
DATA STRUCTURES AND APPLICATIONS (BCS304)
Parent
In a tree data structure, the node which is a predecessor of any node is called as PARENT NODE. In
simple words, the node which has a branch from it to any other node is called a parent node. Parent
node can also be defined as "The node which has child / children".
Child: In a tree data structure, the node which is descendant of any node is called as CHILD
Node. In simple words, the node which has a link from its parent node is called as child node. In a
tree, any parent node can have any number of child nodes. In a tree, all the nodes except root are
child nodes.
Page 34
DATA STRUCTURES AND APPLICATIONS (BCS304)
Sub-trees:In a tree data structure, each child from a node forms a subtree recursively. Every child
node will form a subtree on its parent node.
Internal Nodes:
In a tree data structure, nodes other than leaf nodes are called as Internal Nodes. The root node is also
said to be Internal Node if the tree has more than one node. Internal nodes are also called as 'Non-
Terminal' nodes.
Non-terminals: The nodes other than leaf nodes are called non terminals.
Page 35
DATA STRUCTURES AND APPLICATIONS (BCS304)
Leaf node: A node that has no children is called the leaf node or the terminal node.
Path:A sequence of consecutive edges is called a path. In a tree data structure, the sequence of
Nodes and Edges from one node to another node is called as PATH between that two
Nodes. Length of a Path is total number of nodes in that path. In below example the path A - B -
E - J has length 4.
Page 36
DATA STRUCTURES AND APPLICATIONS (BCS304)
Degree
In a tree data structure, the total number of children of a node is called as DEGREE of that Node. In
simple words, the Degree of a node is total number of children it has. The highest degree of a node
among all the nodes in a tree is called as 'Degree of Tree'
Degree of a node: Degree of a node is equal to the number of children that a node has. The degree
of a leaf node is zero.
The degree of a tree :The degree of a tree is the maximum degree of the nodes in the tree.
Level:Every node in the tree is assigned a level number in such a way that the root node is at
level 1, children of the root node are at level number 2. Thus, every node is at one level higher
than its parent. So, all child nodes have a level number given by parent’s level number + 1.
Page 37
DATA STRUCTURES AND APPLICATIONS (BCS304)
Height of the tree:In a tree data structure, the total number of edges from leaf node to a
particular node in the longest path is called as HEIGHT of that Node. In a tree, height of the
root node is said to be height of the tree. In a tree, height of all leaf nodes is '0'.
Height of the tree:is the maximum distance between the root node of the tree and the leaf node of the
tree.
Depth of the tree:In a tree data structure, the total number of egdes from root node to a
particular node is called as DEPTH of that Node. In a tree, the total number of edges from root
node to a leaf node in the longest path is said to be Depth of the tree. In simple words, the
highest depth of any leaf node in a tree is said to be depth of that tree. In a tree, depth of the
root node is '0'.
Ancestor node: An ancestor of a node is any predecessor node on the path from root to that node.
The root node does not have any ancestors.
Page 38
DATA STRUCTURES AND APPLICATIONS (BCS304)
Descendant node: A descendant node is any successor node on any path from the node to a leaf
node. Leaf nodes do not have any descendants.
3.9.Binary Trees
A binary tree is an important type of tree structure which occurs very often. It is characterized by
the fact that any node can have at most two branches, i.e., there is no node with degree greater than
two. For binary trees we distinguish between the sub-tree on the left and on the right, whereas for
trees the order of the sub-trees was irrelevant. Also a binary tree may have zero nodes. Thus a
binary tree is really a different object than a tree.
Definition: A binary tree is a finite set of nodes which is either empty or consists of a root and two
disjoint binary trees called the left subtree and the right subtree.
The distinctions between a binary tree and a tree should be analyzed. First of all there is no tree
having zero nodes, but there is an empty binary tree. The two binary trees in Fig. 3.9 are different.
The first one has an empty right subtree while the second has an empty left subtree. If the above
are regarded as trees, then they are the same despite the fact that they are drawn slightly
differently.
Page 39
DATA STRUCTURES AND APPLICATIONS (BCS304)
General tree is a tree in which each node can Whereas in binary tree, each node can have at
have many children or nodes. most two nodes.
The subtree of a general tree do not hold the While the subtree of binary tree hold the ordered
ordered property. property.
In general tree, a node can have at While in binary tree, a node can have at
most n(number of child nodes) nodes. most 2(number of child nodes) nodes.
In general tree, there is either zero subtree or While in binary tree, there are mainly two
many subtree. subtree: Left-subtree and Right-subtree.
Page 40
DATA STRUCTURES AND APPLICATIONS (BCS304)
(1) The maximum number of nodes on level i of a binary tree is 2 i-1, i ≥1.
Proof:
Step 1: The proof is by induction on i. Induction Base: The root is the only node on level i = 1.
Hence, the maximum number of nodes on level i =1 is 2i-1 = 20 = 1.
Step 2: Induction Hypothesis: Let i be an arbitrary positive integer greater than 1. Assume that
the maximum number of nodes on level i -1 is 2i-2
Page 41
DATA STRUCTURES AND APPLICATIONS (BCS304)
Step 3: Induction Step: The maximum number of nodes on level i-1 is 2i-2 by the induction
hypothesis. Since each node in a binary tree has a maximum degree of 2, the maximum number of
nodes on level i is two times the maximum number of nodes on level i-1, i.e or 2*2i-2= 2i-1
(2) The maximum number of nodes in a binary tree of depth k is ∑𝒌𝒊=𝟏 = ∑𝒌𝒊=𝟏 𝟐𝒊−𝟏 =𝟐𝒌−𝟏
Lemma– 3:
For any nonempty binary tree, T, if no is the number of terminal nodes and n2 the
number of nodes of degree 2, then n0 = n2 + 1.
Proof:
Consider the binary tree in the Fig. 3.11. each node in the tree should have a maximum of 2
children. A node may not have any child or it can have single child or it can have 2 children.
But a node in a binary tree can not have more that 2 children.
Page 42
DATA STRUCTURES AND APPLICATIONS (BCS304)
Hence it is proved that for any nonempty binary tree, T, if no is the number of terminal nodes and n2
the number of nodes of degree 2, then n0 = n2 + 1.
Page 43
DATA STRUCTURES AND APPLICATIONS (BCS304)
2. Linked representation:
While the above representation appears to be good for complete binary trees it is wasteful
for many other binary trees. In addition, there presentation suffers from the general
inadequacies of sequential representations. Insertion or deletion of nodes from the middle
of a tree requires the movement of potentially many nodes to reflect the change in level
number of these nodes.
These problems can be easily overcome through the use of a linked representation. Each
node will have three fields LCHILD, DATA and RCHILD as in Fig.3.12.2.
Ex: Consider a binary tree in the Fig. 3.12.3: The linked representation of this tree is given in the
Fig. 3.12.3.(b).it can be represented in the memory as shown
Page 44
DATA STRUCTURES AND APPLICATIONS (BCS304)
3.13.3.Inorder traversal
To traverse a non-empty binary tree in inorder, the following operations are performed recursively at
each node. The algorithm works by:
1. Traversing the left sub-tree,
2. Visiting the root node
3. Traversing the right sub-tree.
Page 46
DATA STRUCTURES AND APPLICATIONS (BCS304)
Function code:
void inorder(struct treeNode *node)
{
if (node != NULL)
{
inorder(node->left);
printf("%d", node->data);
inorder(node->right);
}
return;
}
Page 47
DATA STRUCTURES AND APPLICATIONS (BCS304)
Step 2: Elements on the left side of the root node in the in-order traversal sequence
form the left sub-tree of the root node. Similarly, elements on the right side of the root
node in the in-order traversal sequence form the right sub-tree of the root node
Step 3: Recursively select each element from post-order traversal sequence and create
its left and right sub-trees from the in-order traversal sequence. Look at Fig.3.13.3 be
which constructs the tree from its traversal results. Now consider the in-order traversal
and post-order traversal sequences of a given binary tree.
Page 48
DATA STRUCTURES AND APPLICATIONS (BCS304)
Example 2:
Here we can use a stack to perform inorder traversal of a Binary Tree. Below is the algorithm for
traversing a binary tree using stack.
Create an empty stack (say S).
Initialize the current node as root.
Push the current node to S and set current = current->left until current is NULL
If current is NULL and the stack is not empty then:
o Pop the top item from the stack.
o Print the popped item and set current = popped_item->right
o Go to step 3.
If current is NULL and the stack is empty then we are done.
Page 49
DATA STRUCTURES AND APPLICATIONS (BCS304)
Example1:
Example2:
Page 50
DATA STRUCTURES AND APPLICATIONS (BCS304)
Example2:
Page 51
DATA STRUCTURES AND APPLICATIONS (BCS304)
In level order traversal nodes of tree are traversed level-wise from left to right.
Queue data structure is used to store nodes level wise so that each node’s children are visited.
Page 52
DATA STRUCTURES AND APPLICATIONS (BCS304)
At level 0, we process the root node first, followed by the left and right children at level 1.
(assuming the order from left to right).
Similarly, at the second level, we first process the children of the left child of the root then
process the children of the right child. This process goes on for all the levels in the tree.
Page 53
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 54
DATA STRUCTURES AND APPLICATIONS (BCS304)
..
Page 55
DATA STRUCTURES AND APPLICATIONS (BCS304)
There should be no loose threads in threaded binary tree. But in Figure B two threads have
been left dangling: one in the left child of H, the other in the right child of G.
Page 56
DATA STRUCTURES AND APPLICATIONS (BCS304)
In above figure the new threads are drawn in broken lines. This tree has 9 node and 10 Null-
links which has been replaced by threads. When trees are represented in memory, it should be
able to distinguish between threads and pointers. This can be done by adding two additional
fields to node structure, ie., leftThread and rightThread
If ptr→leftThread = TRUE, then ptr→leftChild contains a thread, otherwise it contains
apointer to the left child.
If ptr→rightThread = TRUE, then ptr→rightChild contains a thread, otherwise it contains
pointer to the right child.
Node Structure: The node structure is given in C declaration
Page 57
DATA STRUCTURES AND APPLICATIONS (BCS304)
The complete memory representation for the tree of figure is shown in Figure C .
The variable root points to the header node of the tree, while root →leftChild points to the start
of the first node of the actual tree.
This is true for all threaded trees. Here the problem of the loose threads is handled by pointing
to the head node called root.
Page 58
DATA STRUCTURES AND APPLICATIONS (BCS304)
Question Bank
.
1. Give a node structure to create a doubly linked list of integers and write a C function to perform
the following.
a. Create a three-node list with data 10, 20 and 30
b. Inert a node with data value 15 in between the nodes having data values 10 and 20
c. Delete the node which is followed by a node whose data value is 20
d. Display the resulting singly linked list..
2. Write a note on: i. Linked representation of sparse matrix ii. Doubly linked list.
3. Write a function to insert a node at front and rear end in a circular linked list. Write down sequence
of steps to be followed.
10. Write a C program to perform the following operations on doubly linked list: i. Insert a node ii.
Delete a node.
11. Write a C function to insert a node at front and delete a node from the rear end in a circular linked
list.
12. Describe the doubly linked lists with advantages and disadvantages. Write a C function to delete a
node from a circular doubly linked list with header node.
13. Write a C function for the concatenation of linked lists.
14. Write a C function to perform the following i. Reversing a singly linked list ii. Concatenating
singly linked list. iii. Finding the length of the circular linked list. iv. To search an element in the
singly linked list
15. Write a node structure of linked stack. Write a function to perform push and pop operations on
linked stack.
16. List out the differences between doubly linked list over singly linked list. Write a C functions to
perform the following i. Inserting a node into a doubly linked circular list ii. Deletion from a
doubly linked circular list.
17. Given 2 singly linked lists. LIST-1 and LIST-2. Write an algorithm to form a new list LIST-3
using concatenation of the lists LIST-1 and LIST-2.
18. Write a note on header linked list. Explain the widely used header lists with diagrams. 23.
Illustrate with examples how to insert a node at the beginning, INSERT a node at intermediate
position, DELETE a node with a given value
Page 59
DATA STRUCTURES AND APPLICATIONS (BCS304)
19. List out any 2 differences between doubly linked lists and singly linked list, Illustrate with
example the following operations on a doubly linked list: i. Inserting a node at the beginning. ii.
Inserting at the intermediate position. iii. Deletion of a node with a given value
20. For the given sparse matrix write the diagrammatic linked list representation
Page 60
DATA STRUCTURES AND APPLICATIONS (21CS32)
26. Suppose following sequence lists the node of binary tree in preorder and inorder
respectively, draw diagram of the tree:
Preorder: G B Q A C K F P D E R H
Inodrer: Q B K C F A G P E D H R
27. What is threaded binary tree? Explain with example
Page 61