Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views178 pages

Data Structure (Sdot)

The document provides an overview of linked lists, a dynamic data structure consisting of nodes that hold data and pointers to the next node. It discusses the advantages and drawbacks of linked lists compared to arrays, including types such as singly, doubly, and circular linked lists, along with their operations. Additionally, it outlines basic operations, creation methods, and comparisons with arrays, as well as sorting and searching techniques.

Uploaded by

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

Data Structure (Sdot)

The document provides an overview of linked lists, a dynamic data structure consisting of nodes that hold data and pointers to the next node. It discusses the advantages and drawbacks of linked lists compared to arrays, including types such as singly, doubly, and circular linked lists, along with their operations. Additionally, it outlines basic operations, creation methods, and comparisons with arrays, as well as sorting and searching techniques.

Uploaded by

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

LINKED-LIST

•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?

● The size of arrays is fixed : We must know the


limit on the number of elements to be stored in
advance.
● Inserting a new element and deleting an
element in an array is expensive
● So, advantages of linked list are:
1) Dynamic size
Drawbacks of linked list:

● Random access is not allowed :


We can’t do binary search in linked list.
● Extra memory space for pointer is required
with each element of the list.
LINKED-LIST

•Nodes in a linked list are connected by pointers.


Linked Lists
Each node of the list contains
• the data item
• a pointer to the next node

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

There are 3 different implementations of Linked List available, they are:

•Singly Linked List


•Doubly Linked List
•Circular Linked List
Singly Linked List

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

● Nodes in a linked list are linked together using a


next field, which stores the address of the next
node in the next field of the previous node i.e.
each node of the list refers to its successor and
the last node contains the NULL reference.
● Each node in a list consists of two parts:
1) data
2) pointer to the next node
the elements are linked using pointers
the elements are linked using pointers

Ex.

350
Node 1 Node 2
Node 3

33 900 44 150 55 NULL

Memory
Address 350 900 150
Pictured representation

DATA NEXT

Contains the address of


Contains the actual the next node
data of the list
DOUBLY LINKED-LIST

● 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

called the tail of the list


DOUBLY LINKEDLIST

Data represents the data value stored in the node

Previous represents a pointer that points to the previous node

Next represents a pointer that points to next node in the list


DOUBLY LINKED-LIST APPLICATION

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

● insert − Inserts an element at the start of the list

● delete − Deletes an element from the start of the list

● display − Displays the list


Creation and Insertion
Doubly Linked list

● Doubly Linked List

We add a pointer to the previous node in a


doubly-linked list. Thus, we can go in either
direction: forward or backward.
Doubly Linked list

Node is represented as :
struct node {

int data;
struct node *next;
struct node *prev;
}
Doubly Linked list :

// Class for Doubly Linked List


public class DLL {
Node head; // head of list

/* Doubly Linked list Node*/


class Node {
int data;
Node prev;
Node next;

// Constructor to create a new node


// next and prev is by default initialized as null
Node(int d) { data = d; }
}
}
Doubly Linked list : Create new node

struct node {
int data;
struct node *next;
struct node *prev;
}

Create new node:

struct node *newNode = (struct node*)malloc(siz


eof(struct node));
newNode->data = data;
Circular Linked list : Create new node

A circular linked list is a variation of a linked list in which the last element is linked to the first
element

A circular linked list can be either singly linked or doubly linked .


CIRCULAR LL :

Create three-member circular singly linked list

//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 :

#include <stdio.h> int main(void) {


#include <stdlib.h> Node* head = malloc(sizeof(Node));
typedef struct Node { head->data = 5;
int data; head->next = NULL;
struct Node *next; Node* second = malloc(sizeof(Node));
} Node; second->data = 10;
second->next = NULL;
int isCircular(Node *head) { head->next = second;
Node *temp = head->next; Node* third = malloc(sizeof(Node));
while(temp != NULL && temp != head) { third->data = 15;
temp = temp->next; third->next = NULL;
} second->next = third;
return head == temp;} // third->next = head;
if(isCircular(head)) {
void display(Node *head) { printf("Yes");
Node *temp = head; } else {
while(temp != NULL) { printf("No");
printf("%d ", temp->data); }
temp = temp->next; return 0;
}} }
LINKED LIST AND ARRAY

What is difference between linked list and array?


ARRAY :
● An array is a collection of elements of a similar data type.
● Memory is allocated during the compile time (Static memory allocation).
Size of the array must be specified at the time of array declaration/initialization.

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

● In Java, here is how we can declare an 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

Operations performed on arrays Operations performed on Linked List


•Creation of array •Creation

•Traversing an array •Traversing

•Insertion of new elements •Insertion

•Deletion of required elements. •Deletion

•Modification of an element. •Searching

•Merging of arrays •Concatenation


•Display
Arrays

IN JAVA
ARRAY

Access Array Elements

Each element in an array is associated with a


number. The number is known as an array index.
We can access elements of an array by using
those indices. For example,
ARRAY

Syntax to Declare an Array in Java


dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
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

Declaration, Instantiation and Initialization


int a[]={33,3,4,5};
EXAMPLE:
class Main{
public static void main(String args[]){
int a[]={33,3,4,5};
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}}
ARRAY :

Basic Operations on Arrays

Insert — Inserts an element at a given index


Get — Returns the element at a given index
Delete — Deletes an element at a given index
Size — Gets the total number of elements in an
array
OPERATIONS :

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

How many types of arrays in java? What is it ?

1. One dimensional (1-D) arrays or Linear arrays


2. Multi dimensional arrays
(a) Two dimensional (2-D) arrays or Matrix arrays
(b) Three dimensional arrays
ARRAY : FAQ

Disadvantage of Array

● We have to declare Size of an array in advance.


However, we may not know what size we need
at the time of array declaration.

● The array is static structure. It means array size


is always fixed, so we cannot increase or
decrease memory allocation.
SORTING
TECHNIQUES

● A Sorting Algorithm is used to rearrange a given array or list elements


according to a comparison operator on the elements.

● The comparison operator is used to decide the new order of element in


the respective data structure.
BUBBLE
SORT

● It is the simplest sort method which performs sorting by repeatedly moving the
largest element to the highest index of the array.

● It comprises of comparing each element to its adjacent element and replace


them accordingly.
IMPLEMENTING BUBBLE
SORT

● 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

public class Main {


public static void main(String[] args) {
int[] a = {10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(int i=0;i<10;i++)
{
for (int j=0;j<10;j++)
{
if(a[i]<a[j])
{
int temp = a[i];
a[i]=a[j];
a[j] = temp;
}}}
for(int i=0;i<10;i++)
{
System.out.println(a[i]);
}}}
SELECTION
SORT
The selection sort algorithm sorts an array by repeatedly finding the
minimum element (considering ascending order) from unsorted part and
putting it at the beginning. The algorithm maintains two sub arrays in a
given array.

● The sub array which is already sorted.

● Remaining sub array which is unsorted.


IMPLEMENTING SELECTION
SORT

● Find the minimum element in the list.

● Swap it with the element in the first position of the list.

● Repeat the steps above for all remaining elements of the list starting
from the second position.
IMPLEMENTING SELECTION
SORT
INSERTION
SORT

• Removes an element from an array


• Compares it against the largest value in the array
• Moves the element to its correct location.
IMPLEMENTING INSERTION
SORT
SEARCHING
TECHNIQUES

● Searching is an operation or a technique that helps finds the place of a


given element or value in the list.

● Any search is said to be successful or unsuccessful depending upon


whether the element that is being searched is found or not.
SEARCHING
TECHNIQUES

● Some of the standard searching technique that is being followed in the


data structure is listed below:

● Linear Search or Sequential Search

● Binary Search
LI●NEATRraSveErAseRCthHe
array

● Match the key element with array element

● If key element is found, return the index position of the array element

● Step 4: If key element is not found, return -1


LINEAR
SEARCH
BINARY
SEARCH

● Binary Search: binary search or half-interval search algorithm finds the


position of a specified value (the input "key") within a sorted array.

● 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

Binary Search Pseudocode …


if(size == 0) found = false;
else {
middle = index of approximate midpoint of
array segment;
if(target == a[middle])
target has been found!
else if(target < a[middle])
search for target in area before midpoint;
else
search for target in area after midpoint; }
2D
ARRAY

• An array of more than one dimension is known as a multi-dimensional


array.
• Two of the most common examples of multi-dimensional arrays are two
and three-dimensional array, known as 2D and 3D array, anything above
is rare.
2D
ARRAY

• Two – dimensional array is the simplest form of a multidimensional


array.
• A two – dimensional array can be seen as an array of one – dimensional
array for easier understanding.
SYNTA
X

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

Sample InputSample Output


55
11111
10001
10001
10001
11111
Java 2D Array

import java.util.Scanner; else


import java.io.*; a[i][j]=0;
class Main { }}
static int m,n,i=0,j=0; obj.print(m,n);
static int a[][]=new int [100][100]; }
public static void main(String public void print(int m,int n)
[]args) { {
Main obj = new Main(); for(i=0;i<m;i++)
int m,n; {
Scanner in=new Scanner(System.in); for(j=0;j<n;j++)
m=in.nextInt(); {
n=in.nextInt(); System.out.print(a[i][j]+" " );
for(i=0;i<m;i++) }
{ System.out.println();}} }
for(j=0;j<n;j++)
{
if((i==0)||(j==0)||(i==m-
1)||(j==n-1))
a[i][j]=1;
QUESTION

Which of these is an incorrect array declaration?


a) int arr[] = new int[5];
b) int [] arr = new int[5];
c) int arr[] = new int[5];
d) int arr[] = int [5] new

Answer : d
QUESTION

What will be the output of the following Java code?


class array_output {
public static void main(String args[]) {
int array_variable [] = new int[10];
for (int i = 0; i < 10; ++i) {
array_variable[i] = i;
System.out.print(array_variable[i] + " ");
i++; } } }
a) 0 2 4 6 8
b) 1 3 5 7 9
c) 0 1 2 3 4 5 6 7 8 9
d) 1 2 3 4 5 6 7 8 9 10

Answer : a
QUESTION

What will be the output of the following Java code?


class evaluate {
public static void main(String args[]) {
int arr[] = new int[] {0 , 1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = 6;
n = arr[arr[n] / 2];
System.out.println(arr[n] / 2);
} }
a) 3
b) 0
c) 6
d) 1

Answer : d
QUESTION

What will be the output of the following Java code?


class array_output {
public static void main(String args[]) {
int array_variable[][] = {{ 1, 2, 3}, { 4 , 5, 6}, { 7, 8, 9}}; int sum = 0;
for (int i = 0; i < 3; ++i){
for (int j = 0; j < 3 ; ++j){
sum = sum + array_variable[i][j];}}
System.out.print(sum / 5);
} }
a) 8
b) 9
c) 10
d) 11

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?

• A stack is called a last-in-first-out (LIFO) collection. This means that the


last thing we added (pushed) is the first thing that gets pulled (popped) off.
• A stack is a sequence of items that are accessible at only one end of the
sequence.
• A stack has a restriction that insertion and deletion of element can only be
done from only one end of stack and we call that position as top. The
element at top position is called top element. Insertion of element is
called PUSH and deletion is called POP.
Operation on 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.

Peek or Top: Returns top element of stack.

isEmpty: Returns true if stack is empty, else false.


Operation on Stack

push( x ) : insert element x at the top of stack.

begin procedure push: stack, data


if stack is full
return null
endif
top ← top + 1
stack[top] ← data
end procedure
Operation on Stack

push( x ) : insert element x at the top of stack.

void push(int data) {


if(!isFull()) {
top = top + 1;
stack[top] = data;
}
else {
printf("Could not insert data, Stack is full.\n"); } }
Operation on Stack

pop( ) : removes element from the top of stack.

begin procedure pop: stack


if stack is empty
return null
endif
data ← stack[top]
top ← top - 1
return data
end procedure
Operation on Stack

pop( ) : removes element from the top of stack.

int pop(int data) {


if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
}
else {
printf("Could not retrieve data, Stack is empty.\n");
}}
Operation on Stack

isEmpty ( ) : check whether the stack is empty or not..

begin procedure isempty


if top less than 1
return true
else
return false
endif
end procedure
Operation on Stack

isEmpty ( ) : check whether the stack is empty or not..

bool isEmpty ( ) {
if ( top == -1 )
return true ;
else
return false;
}
Operation on Stack

isFull() − check if stack is full

begin procedure isfull


if top equals to MAXSIZE
return true
else
return false
endif
end procedure
Operation on Stack

isfull() − check if stack is full..

bool isfull() {
if(top == MAXSIZE)
return true;
Else
return false;
}
Operation on Stack

size ( ) : tells the current size of 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

Checking the validity of an expression


containing nested parenthesis:
Example:
VALID INPUTS INVALID INPUTS

{} {(}
([(()])
({[]})
{}[])
{[]()} [{)}(]}]
[ { ( { } [ ] ( { })}]
OPEN parthensis -- push into the stack eg:{[(
Close - pop element from stack eg:]
})
{([])} {

{- invalid

Empty-- valid or
balanced
Application of Stack

CHECKING BALANCED PARTHENSIS ARE NOT


static boolean areParenthesisBalanced(char exp[]){
stack st=new stack();
for(int i=0;i<exp.length;i++) {
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
st.push(exp[i]);

if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') {


if (st.isEmpty()) {
return false;
}
else if ( !isMatchingPair(st.pop(), exp[i]) )
{
return false;
} } }

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

● POSTFIX notation: e.g, AB+


CONVERSION FROM INFIX TO POSTFIX

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*/

READING OF POSTFIX STACK TOP EXPRESSION


A A A
B AB AB

- (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

* ((D+E)*F) (A-B) ((D+E)*F)


/ (A-B) /((D+E)*F) (A-B) /((D+E)*F)

(A-B) /((D+E)*F)
CONVERSION FROM POSFIX TO INFIX

EXAMPLE: +-*AB/CDE -- MAKE IT REVERSE EDC/BA*-+

READING STACK TOP EXPRESSION


E E E
D D ED

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

Conversion of INFIX to POSTFIX


conversion:
2+(4-1)*3

ANS:241-3*+
EVALUATION OF POSTFIX EXPRESSION PROGRAM

static int evaluatePostfix(String exp) {


Stack<Integer> stack=new Stack<>();
for(int i=0;i<exp.length();i++) {
char c=exp.charAt(i);
if(Character.isDigit(c))
stack.push(c - '0'); {
int val1 = stack.pop();
int val2 = stack.pop();
switch(c) {
case '+':
stack.push(val2+val1);
break;
case '-':
stack.push(val2- val1);
break;
case '/':
stack.push(val2/val1);
break;
case '*':
stack.push(val2*val1);
break;
} } }
return stack.pop();
}
QUEUE
What is a queue?
• Queues have two ends:
– Elements are added at one end.
– Elements are removed from the other end.
• The element added first is also removed first (FIFO: First In, First Out).
Enqueue: Add an element to the end of the queue
Dequeue: Remove an element from the front of the queue
isempty: Check if the queue is empty
isfull: Check if the queue is full
Peek: Get the value of the front of the queue without removing it
How Queue Works
How Queue Works
Operation on QUEUE

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.

int enqueue(int data)


if(isfull())
return 0;
rear = rear + 1;
queue[rear] = data;
return 1;
end procedure
Operation on QUEUE

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

Types of Queues in Data Structure


•Queue in data structure is of the following types
•Simple Queue
•Circular Queue
•Priority Queue
•Dequeue (Double Ended 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.

Doubly Ended Queue (Dequeue)


The doubly ended queue or dequeue allows the insert and delete operations from both
ends (front and rear) of the queue.
TREE
TREE

● 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

● Full binary tree


● Perfect Binary Tree
● Complete Binary Tree
● Balanced Binary Tree
REPRESENTATION

struct node {
Int data;
struct node* left;
struct node* right;
}
TREE TRAVERSAL

●Inorder traversal (LNR)


●Preorder traversal(NLR)
●Postorder traversal (LRN)

Ignored traversal inorder(root->left)


● First, visit all the nodes in the left subtree display(root->data)
● Then the root node inorder(root->right)
● Visit all the nodes in the right subtree

Preorder traversal display(root->data)


● Visit root node preorder(root->left)
● Visit all the nodes in the left subtree preorder(root->right)
● Visit all the nodes in the right subtree

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

How to construct binary search tree?


10

5 15

25

20 30

35
RECONSTRUCT TREE

INSERT 8 in this 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 tree is a self-balancing binary search tree in


which each node maintains an extra information
called as balance factor whose value is either -1,
0 or +1.

Balance Factor = (Height of Left Subtree - Height


of Right Subtree)
AVL TREE
AVL TREE

AVL Rotations

To balance itself, an AVL tree may perform the


following four kinds of rotations

● Left rotation
● Right rotation
● Left-Right rotation
● Right-Left rotation
AVL Rotations

Left rotation :

If a tree becomes unbalanced, when a node is


inserted into the right subtree of the right
subtree, then we perform a single left rotation
AVL Rotations

Right rotation :

AVL tree may become unbalanced, if a node is


inserted in the left subtree of the left subtree.
The tree then needs a right rotation.
AVL Rotations

Left Right rotation :

A left-right rotation is a combination of left


rotation followed by right rotation.
AVL Rotations

Right left rotation :


The second type of double rotation is Right-Left Rotation. It is a combination of right
rotation followed by left rotation.
Construct a binary tree by using postorder and
inorder sequences given below.
Inorder: N, M, P, O, Q
Postorder: N, P, Q, O, M
a) C c)

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

A graph is a pictorial representation of a set of objects where some pairs of


objects are connected by links. The interconnected objects are represented by
points termed as vertices, and the links that connect the vertices are
called edges.
Formally, a graph is a pair of sets (V, E), where V is the set of vertices and E is
the set of edges, connecting the pairs of vertices.

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

In order to store some graph into the computer's memory.


There are two ways to store Graph into the computer's memory.
1. Adjacency Matrix (Sequential represntation)
2. Adjacency list (Linked respresentation)

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

We have n = 4, thus the maximum number of possible spanning trees is


equal to 44-2 = 16. Thus, 16 spanning trees can be formed from the above graph.
Example of a Spanning Tree

Minimum Spanning Tree


A minimum spanning tree is a spanning tree in which the sum of the weight of the edges is as
minimum as possible

Weighted Graph
Example of a Spanning Tree

Minimum Spanning Tree

• -------Minimum Spanning Tree



GRAPH TRAVERSAL

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

Depth First Search (DFS) Algorithm


Depth first search (DFS) algorithm starts with the initial node of the graph
, and then goes to deeper and deeper until we find the goal node or the node
which has no children. The algorithm, then backtracks from the dead end towards
the most recent node that is yet to be completely unexplored.
The data structure which is being used in DFS is stack. In DFS, the
edges that leads to an unvisited node are called discovery edges while the edges
that leads to an already visited node are called block edges.
GRAPH TRAVERSAL

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

Breadth first search


Breadth first search is a graph traversal algorithm that starts traversing the graph
from root node and explores all the neighbouring nodes. Then, it selects the
nearest node and explore all the unexplored nodes.
The data structure which is being used in BFS is Queue.
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

● What is data structure?


● What are doubly linked lists?
● What is an AVL tree?
● What is Huffman’s algorithm?
● How do you search for a target key in a linked list?
● Differentiate linear from a nonlinear data structure.
● What are the parts of a linked list?
● What is bubble sort and how bubble sort works?
● What is the prefix and post fix notation of (a + b) * (c + d) ?
● What is tree traversal?
● What are some of the applications of DS?

You might also like