Data Structure (Sdot)
Data Structure (Sdot)
•Linked List is a very commonly used linear data structure which consists of group of nodes in a
sequence.
•Each node holds its own data and the address of the next node hence forming a chain like
structure.
Why linked list?
Data Next
object
Linked Lists
• Collection structure has a pointer to the list
head
node
Head
Data Next
object
Linked Lists
Collection
Head
node
node
Data Next
Data Next
object2
object
Types of Linked Lists
Singly linked lists contain nodes which have a data part as well as an address part i.e. next, which
points to the next node in the sequence of nodes.
The operations we can perform on singly linked lists are insertion, deletion and traversal
Representation
Ex.
350
Node 1 Node 2
Node 3
Memory
Address 350 900 150
Pictured representation
DATA NEXT
● Doubly Linked List is a variation of the linked list. The linked list is a linear data
structure which can be described as the collection of nodes. Nodes are connected
through pointers
● Each node contains two fields: data and pointer to the next field
● The first node of the linked list is called the head, and the last node of the list is
Each node in a double linked list has a pointer the previous and next node, it is easy to
implement skip forward/backward functionality
The pointer to the next node also makes it quite easy to start the next track when a track is
over.
When you add a new track to a playlist, you tack it on to the end
Data Structure Concepts
● Collection of nodes
● Contains two parts – Data and next
● Last lode(next=NULL)
● First node – Head node
CIRCULAR LINKED LIST
Circular Linked List is a variation of Linked list in which the first element points to the
last element and the last element points to the first element. Both Singly Linked List
and Doubly Linked List can be made into a circular linked list
SINGLY LINKED LIST AS CIRCULAR
In singly linked list, the next pointer of the last node points to the first node
DOUBLY LINKED LIST AS CIRCULAR
In doubly linked list, the next pointer of the last node points to the first node and the
previous pointer of the first node points to the last node making the circular in both
directions
BASIC OPERATIONS
Node is represented as :
struct node {
int data;
struct node *next;
struct node *prev;
}
Doubly Linked list :
struct node {
int data;
struct node *next;
struct node *prev;
}
A circular linked list is a variation of a linked list in which the last element is linked to the first
element
//ALLOCATE MEMORY
Node* first = malloc(sizeof(Node));
Node* Second= malloc(sizeof(Node));
Node* Third= malloc(sizeof(Node));
//ASSIGN VALUES
//CONNECT NODES
one->next = two;
two->next = three;
three->next = one;
CIRCULAR LL :
LINKED LIST :
● Linked List is an ordered collection of elements of the same type in which each element is
connected to the next using pointers.
● Memory is allocated during the run-time (Dynamic memory allocation)
● Size of a Linked list grows/shrinks as and when new elements are inserted/deleted.
ARRAY
dataType[ ] arrayName;
dataType - it can be primitive data types like int,
char, double, byte, etc. or Java objects
LINKED-LIST AND ARRAY
LINKED-LIST AND ARRAY
LINKED-LIST AND ARRAY
IN JAVA
ARRAY
● Arrays are used to store lots of similar data in one variable instead of multiple
variables
● If we want to store the scores (or runs) of various cricket teams, we can either have
india_score, pak_score, aus_score, srilanka_score or simply scores which contains
the scores of all teams
ARRAY
INSERT:
class Main {
public static void main(String[] args) {
int arr[]={1,2,3,4,5,0};
int indexToinsert=1; int n=arr.length;
for(i=n-1; i>indexToinsert; i--){ int indexToinsert=1;
arr[i]=arr[i-1]; for(int i=n-1; i>indexToinsert; i--){
}
arr[i]=arr[i-1];
arr[indexToinsert]=element;
}
arr[indexToinsert]=9;
for(int i:arr) {
I/P -- 1 2 5 6 7 8 0 System.out.println(i);
O/P--1 9 2 5 6 7 8 }
}
}
OPERATIONS :
DELETE:
class Main {
public static void main(String[] args) {
int arr[]={1,2,3,4,5,0};
int indexTodelete=1; int n=arr.length;
for(i=indexTodelete;i<n-1;i++){
arr[i]=arr[i+1];
int indexTodelete=1;
} for(int i=indexTodelete;i<n-1;i++){
arr[i]=arr[i+1];
}
for(int i:arr) {
I/P -- 1 2 5 6 7 8 0 System.out.println(i);
O/P--1 5 6 7 8 }
}
}
OPERATIONS :
UPDATE:
class Main {
Int indexToupdate=2; public static void main(String[] args) {
Int element=300; int arr[]={1,2,3,4,5,0};
int n=arr.length;
int index=2;
int element=300;
arr[index]=element;
for(index=0;index<n;index++){
System.out.println(arr[index]);
I/P -- 1 2 5 6 7 8 0 }
O/P--1 3 5 6 7 8 }
}
Java 1D Array
● Array is a simple data structure used to store a collection of data in a contiguous block of memory.
Each element in the collection is accessed using an index, and the elements are easy to find because
they're stored sequentially in memory.
Java 1D Array
Disadvantage of Array
● It is the simplest sort method which performs sorting by repeatedly moving the
largest element to the highest index of the array.
● Starting with the first element(index = 0), compare the current element
with the next element of the array.
● If the current element is greater than the next element of the array,
swap them.
● If the current element is less than the next element, move to the next
element. Repeat Step 1.
IMPLEMENTING BUBBLE
SORT
IMPLEMENTING BUBBLE
SORT
● Repeat the steps above for all remaining elements of the list starting
from the second position.
IMPLEMENTING SELECTION
SORT
INSERTION
SORT
● Binary Search
LI●NEATRraSveErAseRCthHe
array
● If key element is found, return the index position of the array element
● In each step, the algorithm compares the input key value with the key value of
the middle element of the array.
● If the keys match, then a matching element has been found so its index, or
position, is returned
IMPLEMENTING BINARY
SEARCH
IMPLEMENTING BINARY
SEARCH
DECLARATION:
d a t a t y p e [ ] [ ] arrayname = new
d a t a t yp e [ x] [ y] ;
For example: i n t [ ] [ ] a r r = new i n t [ 1 0 ] [ 2 0 ] ;
INITIALIZATION:
array_name[row_index][column_index] =
v al ue;
For example: a r r [ 0 ] [ 0 ] = 1 ;
ACCESSING 2D
ARRAY
Syntax
:
x[rowindex][columnindex]
For
example:
i n t [ ] [ ] a r r = new i n t [ 1 0 ] [ 2 0 ] ;
arr[0][0] = 1;
Java 2D Array
Q1.
Write a program to print the pattern such that the elements of first row, first column,last row and last
column should be one and the remaining elements should be zero.
Input Format
Given a single line input separated by space.N1 denotes the numbers of row N2 denotes the number of
columns.
Output Format
Print the output in the required format.
Constraints
Integers only.
● 1<N1<100
● 1<N2<100
Java 2D Array
Answer : d
QUESTION
Answer : a
QUESTION
Answer : d
QUESTION
Answer : b
QUESTION
class Main{
public static void main(String[] args){
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
} }
Answer : 0 1 2
3456
78
QUESTION
class Main{
static int[] get(){
return new int[]{10,30,50,90,60};
}
public static void main(String args[]){
int arr[]=get();
for(int i=0;i<arr.length;i++) Answer : 10
System.out.println(arr[i]); 30
}}
50
90
60
STACK
• What is Stack?
• PUSH
• POP
Operation on Stack
Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow
condition.
Pop: Removes an item from the stack. The items are popped in the reversed order in
which they are pushed. If the stack is empty, then it is said to be an Underflow condition.
bool isEmpty ( ) {
if ( top == -1 )
return true ;
else
return false;
}
Operation on Stack
bool isfull() {
if(top == MAXSIZE)
return true;
Else
return false;
}
Operation on Stack
int size ( ) {
return top + 1;
}
Operation on Stack
peek()
Algorithm of peek() function −
begin procedure peek
return stack[top]
end procedure
{([])}
int peek() {
return stack[top ];
}
Application of Stack
{} {(}
([(()])
({[]})
{}[])
{[]()} [{)}(]}]
[ { ( { } [ ] ( { })}]
OPEN parthensis -- push into the stack eg:{[(
Close - pop element from stack eg:]
})
{([])} {
{- invalid
Empty-- valid or
balanced
Application of Stack
if (st.isEmpty())
return true;
else
{
return false;
} }
EXPRESSION
●INFIX notation:
The general way of writing arithmetic
expressions is known as infix notation. e.g,
(a+b)
● PREFIX notation: e.g, +AB
RULES:
1. Priorities of operator
2. No two Operators of same priority can stay
together in stack column * /-
3. Lowest priority can’t be placed before highest
priority *+ -- +
4. (+)- in between parenthesis means pop that
element
CONVERSION FROM INFIX TO POSTFIX
EXAMPLE: (A+B/C*(D+C)-F)
SYMBOL SCANNING STACK POSTFIX EXPRESSION
( (
A ( A
+ (+ A
B (+ AB
/ (+/ AB
C (+/ ABC
* (+* ABC/
( (+*( ABC/
D (+*( ABC/D
+ (+*(+ ABC/D
C (+*(+ ABC/DC
CONVERSION FROM INFIX TO POSTFIX
EXAMPLE: (A+B/C*(D+C)-F)
SYMBOL SCANNING STACK POSTFIX EXPRESSION
) (+*(+)---POP (+* ABC/DC+
- (+*- (+ - (- ABC/DC+*+
F (- ABC/DC+*+F
) (-) -- POP ABC/DC+*+F-
ABC/DC+*+F-
CONVERSION FROM POSFIX TO INFIX
EXAMPLE: AB-DE+F*/
- (A-B) (A-B)
D D (A-B)D
E E (A-B)DE
+ (D+E) (A-B) (D+E)
F F (A-B) (D+E) F
(A-B) /((D+E)*F)
CONVERSION FROM POSFIX TO INFIX
C C EDC
/ (C/D) E(C/D)
B B E(C/D)B
A A E(C/D)B A
* (A*B) E(C/D)(A*B)
- (A*B)-(C/D) E((A*B)-(C/D))
+ ((A*B)-(C/D))+E ((A*B)-(C/D))+E
((A*B)-(C/D))+E
EVALUATION OF POSTFIX EXPRESSION
5,6,2,+,*,12,4,/,-
37
ANS:37
ANS:241-3*+
EVALUATION OF POSTFIX EXPRESSION PROGRAM
peek()
This function helps to see the data at the front of the queue. The algorithm of peek()
function is as follows −
..
int peek() {
return queue[front];
}
Operation on QUEUE
isfull()
As we are using single dimension array to implement queue, we just check for the rear
pointer to reach at MAXSIZE to determine that the queue is full. In case we maintain the
queue in a circular linked-list, the algorithm will differ. Algorithm of isfull() function −
..
bool isfull()
if(rear == MAXSIZE - 1)
return true;
else
return false;
}
Operation on QUEUE
isempty()
If the value of front is less than MIN or 0, it tells that the queue is not yet initialized, hence
empty.
bool isempty() {
if(front < 0 || front > rear)
return true;
else
return false;
}
Operation on QUEUE
Enqueue Operation
Queues maintain two data pointers, front and rear. Therefore, its operations are
comparatively difficult to implement than that of stacks.
Dequeue Operation
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 −
int dequeue() {
if(isempty())
return 0;
int data = queue[front];
front = front + 1;
return data;
}
TYPES OF QUEUE
Simple Queue
Insertion occurs at the rear (end) of the queue and deletions are performed at the front
(beginning) of the queue list. All nodes are connected to each other in a sequential
manner. The pointer of the first node points to the value of the second and so on.
The first node has no pointer pointing towards it whereas the last node has no pointer
pointing out from it.
TYPES OF QUEUE
Priority Queue
Priority queue makes data retrieval possible only through a pre determined priority
number assigned to the data items.
While the deletion is performed in accordance to priority number (the data item with
highest priority is removed first), insertion is performed only in the order.
TYPES OF QUEUE
Circular Queue
Unlike the simple queues, in a circular queue each node is connected to the next node in
sequence but the last node’s pointer is also connected to the first node’s address. Hence,
the last node and the first node also gets connected making a circular link overall.
● A tree is a nonlinear hierarchical data structure that consists of nodes connected by edges.
● Other data structures such as arrays, linked list, stack, and queue are linear data structures that
store data sequentially. In order to perform any operation in a linear data structure, the time
complexity increases with the increase in the data size.
● Different tree data structures allow quicker and easier access to the data as it is a non-linear
data structure.
Tree Terminologies
Tree Terminologies
Node
● A node is an entity that contains a key or value and pointers to its child nodes.
● The last nodes of each path are called leaf nodes or external nodes that do not
contain a
link/pointer to child nodes.
● The node having at least a child node is called an internal node.
Edge
It is the link between any two nodes.
Root
It is the topmost node of a tree.
Height of a Node
The height of a node is the number of edges from the node to the deepest leaf (ie. the
longest path from the node to a leaf node).
Depth of a Node
The depth of a node is the number of edges from the root to the node.
Height of a Tree
The height of a Tree is the height of the root node or the depth of the deepest node.
Tree Terminologies
Path :-
The sequence of consecutive edges is called path. In the tree shown in the above
image, path to the node E is A→ B → E.
Degree of a Node
The degree of a node is the total number of branches of that node.
Ancestor node
An ancestor of a node is any predecessor node on a path from root to that node. The
root node
doesn't have any ancestors.
BINARY TREE
Binary Tree is a special type of generic tree in which, each node can have at most two children.
Binary tree is generally partitioned into three disjoint subsets.
● Root of the node
● left sub-tree which is also a binary tree.
● Right binary sub-tree
TYPES OF BINARY TREE
struct node {
Int data;
struct node* left;
struct node* right;
}
TREE TRAVERSAL
Postorder traversal
● Visit all the nodes in the left subtree postorder(root->left)
● Visit all the nodes in the right subtree postorder(root->right)
● Visit the root node display(root->data)
ORDER
B C
D E F G
K J I H
ORDER
INORDER: ABDKEJCFIGH
PREORDER: DKBJEAIFCGH
POSTORDER: KDJEBIFHGCA
A
B C
D E F G
K J I H
RECONSTRUCT TREE
PREORDER: DKBJEAIFCGH
INORDER: ABDKEJCFIGH
B C
D E F G
K J I H
ORDER
FIND
In-order
Preorder
Post-order 1
2 3
4 5
class Node { System.out.print(node.key + "->");
int key; preorder(node.left);
Node left, right; preorder(node.right); }
public Node(int item) { void postorder() {
key = item; postorder(root);
left = right = null;
}}
}
class BinaryTree { void inorder() {
BinaryTree() { inorder(root);
root = null; }
} void preorder() {
void postorder(Node node) { preorder(root); }
if (node == null) public static void main(String[] args) {
return; BinaryTree tree = new BinaryTree();
postorder(node.left);
postorder(node.right);
tree.root = new Node(1);
System.out.print(node.key + "->"); tree.root.left = new Node(12);
} tree.root.right = new Node(9);
void inorder(Node node) { tree.root.left.left = new Node(5);
if (node == null) tree.root.left.right = new Node(6);
return; System.out.println("Inorder traversal"); tree.inorder();
inorder(node.left); System.out.println("\nPreorder traversal ");
System.out.print(node.key + "->"); tree.preorder();
inorder(node.right); }
void preorder(Node node) {
System.out.println("\nPostorder traversal");
if (node == null) tree.postorder(); } }
return;
BINARY SEARCH TREE
● Binary search tree is a data structure that quickly allows us to maintain a sorted list of numbers.
● It is called a binary tree because each tree node has maximum of two children.
● It is called a search tree because it can be used to search for the presence of a number
in O(log(n)) time.
The properties that separates a binary search tree from a regular binary tree is
● All nodes of left subtree are less than root node
● All nodes of right subtree are more than root node
● Both subtrees of each node are also BSTs i.e. they have the above two properties
RECONSTRUCT TREE
10, 5, 15,25,20,30,35
5 15
25
20 30
35
RECONSTRUCT TREE
10
5 15
25
8
20 30
35
OPERATION OF BINARY SEARCH TREE
SEARCHING
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)
OPERATION OF BINARY SEARCH TREE
INSERT
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;
AVL TREE
AVL Rotations
● Left rotation
● Right rotation
● Left-Right rotation
● Right-Left rotation
AVL Rotations
Left rotation :
Right rotation :
b) d)
ANS: D
Construct a binary search tree by using postorder
sequence given below. Postorder: 2, 4, 3, 7, 9, 8, 5.
a) c)
b) d)
ANS: B
A binary search tree contains values 7, 8, 13, 26,
35, 40, 70, 75. Which one of the following is a
valid post-order sequence of the tree provided
the pre-order sequence as 35, 13, 7, 8, 26, 70, 40
and 75?
a) 7, 8, 26, 13, 75, 40, 70, 35
b) 26, 13, 7, 8, 70, 75, 40, 35
c) 7, 8, 13, 26, 35, 40, 70, 75
d) 8, 7, 26, 13, 40, 75, 70, 35`
ANS: D
Preorder ----- A B D H E C F I G J K
Inorder -------- D H B E A I F C J G K
What will be the postorder?
a. H D E B I F J K G C A
b. H D E B F I J K G C A
c. H D E B I F J K CG A
d. None of the above.
ANSWER: H D E B I F J K G C A
For the tree below, write the pre-order traversal.
a) 2, 7, 2, 6, 5, 11, 5, 9, 4
b) 2, 7, 5, 2, 6, 9, 5, 11, 4
c) 2, 5, 11, 6, 7, 4, 9, 5, 2
d) 2, 7, 5, 6, 11, 2, 5, 4, 9
ANS: A
GRAPH
GRAPH
V = {a, b, c, d, e}
E = {ab, ac, bd, cd, de}
GRAPH(APPLICATION)
.
GRAPH TERMINOLOGIES
Vertex − Each node of the graph is represented as a vertex. In the following example,
the labeled circle represents vertices.
Edge − Edge represents a path between two vertices or a line between two vertices.
Undirected edge - bidirectional
Directed edge - Unidirectional
Weighted edge - edge with cost on it
Mixed Graph : A graph with undirected and directed edge.
Adjacency − Two node or vertices are adjacent if they are connected to each other
through an edge
Path − Path represents a sequence of edges between the two vertices.
Degree of the Node
A degree of a node is the number of edges that are connected with that node. A node
with degree 0 is called as isolated node.
Loop: An edge that is associated with the similar end points can be called as Loop.
GRAPH TERMINOLOGIES
connected graph: is a graph in which there is always a path from a vertex to any other vertex.
GRAPH OPERATION:
1. Insert a vertex
2. Delete a vertex
3. Add an edge
4. Delete an edge
5. Find Vertex
Graph Representation
ADJACENCY MATRIX:
TRY
Graph Representation
Adjacency list:
TRY
Spanning Tree
Spanning tree
• A spanning tree is a sub-graph of an undirected and a connected graph, which
includes all the vertices of the graph having a minimum possible number of edges. If a
vertex is missed, then it is not a spanning tree.
• The edges may or may not have weights assigned to them.
• The total number of spanning trees with n vertices that can be created from a complete
graph is equal to n(n-2).
Normal Graph
Example of a Spanning Tree
Spanning Tree
Weighted Graph
Example of a Spanning Tree
Traversing the graph means examining all the nodes and vertices of the graph.
There are two standard methods by using which, we can traverse the graphs.
Lets discuss each one of them in detail.
•Breadth First Search
•Depth First Search
ALGORITHM:
1. Define a stack size total no of vertices in the graph
2. Select any vertex as starting point for traversal. Visit the vertex
and push it on to the stack
3. Visit any one of the adjacent vertex of the vertex which is at top
of the stack, which is not visited, and push it on to the stack
4. Repeat step 3, Until there are no new vertex to be visit from the
vertex on top of the stack.
5. When there is no new vertex to be visit the use backtracking and
pop one vertex from the stack
6. Repeat step 3,4,5 until stack becomes empty.
7. When stack becomes empty, then produce final spanning tree by
removing unused edges from the graph
GRAPH TRAVERSAL
ALGORITHM:
1. Define a Queue of size total number of vertices in the graph
2. Select any vertex as starting point for traversal. Visit that
vertex and insert it into the queue
3. Visit all the adjacent vertices of the vertex which is at front of
the queue, which is not visited and insert into the queue
4. When there is no new vertex to be visit from the vertex at the
front of the queue then delete that vertex from the queue
5. Repeat step 3 and 4, until queue becomes empty
6. When queue becomes empty, then produce final spanning tree
by removing unused edges from the graph
GRAPH
STRUCTURE:(IN C)
struct node
{
int vertex;
struct node* next;
};
struct Graph
{
int numVertices;
struct node** adjLists;
};
GRAPH
(JAVA)
class Graph
{
private int numVertices;
private LinkedList<integer> adjLists[ ];
}
When does the ArrayIndexOutOfBoundsException occur?
A.) Compile-time
B.) Run-time
C.) Not an error
D.) None of the mentioned
ANSWER: B
What are the disadvantages of arrays?
A.) We must know before hand how many elements will be there in the array
B.) There are chances of wastage of memory space if elements inserted in an array are lesser than
than the allocated size
C.) Insertion and deletion becomes tedious
D.) All of the mentioned
ANSWER: D
What is the time complexity to count the number of elements in the linked list?
a) O(1)
b) O(n)
c) O(logn)
d) O(n2)
ANSWER: B
Linked lists are not suitable to for the implementation of?
A. Insertion sort
B. Radix sort
C. Polynomial manipulation
D. Binary search
ANSWER: D
What would be the asymptotic time complexity to find an element in the linked list?
A.) O(1)
B.) O(n)
C.) O(n2)
D.) None of these
ANSWER: B
In the stack, If user try to remove element from the empty stack then it called as ___________.
A. Underflow of Stack
B Overflow of Stack
C Garbage Collection
D Empty Collection
ANSWER: A
User perform following operations on stack of size 5 then -push(1); pop(); push(2); push(3); pop();
push(4); pop(); pop(); push(5); at the end of last operation, total number of elements present in the
stack are -
A. 4
B. 1
C. 3
D. 2
ANSWER: B
User perform following operations on stack of size 5 then -push(1); pop(); push(2); push(3); pop();
push(2); pop(); pop(); push(4); pop(); pop(); push(5); Which of the following is correct statement for
stack ?
A. Underflow Occures
B. Stack Operations will be performed Smoothly
C. Overflow Occures
D. None of these
ANSWER: A
What is the result of the following postfix expression?
ab*cd*+ where a=2,b=2,c=3,d=4.
a) 16
b) 12
c) 14
d) 10
ANSWER: A
What is the result of the given postfix expression? abc*+ where a=1, b=2, c=3.
a) 4
b) 5
c) 6
d) 7
ANSWER: D
Data Structure