Unit 1
Unit 1
The data structures are also divided into two categories based on the type data they are
organizing
Homogenous Data Structure
In homogenous data structure, all the elements are of same type. Example is
array.
Non Homogenous Data Structure
In non-homogenous structures, all the elements are may or may not be of the
same types. Example is Records.
Based on the memory allocated for the data the data structures are divided into
Dynamic Data Structure:
Dynamic Data Structure (DDS) refers to an organization or collection of data in memory
that has the flexibility to grow or shrink in size, allowing a programmer to control exactly
how much memory is utilized. Dynamic data structures change in size by having unused
memory allocated or de-allocated from the heap as needed.
Static Data Structure:
Static Data Structure is an organization or collection of data in memory that is fixed in
size. This results in the maximum size needing to be known in advance, as memory
cannot be reallocated at a later point. Arrays are a prominent example of a static data
structure.
Characteristics of a Data Structure
Correctness:
Data structure implementation should implement its interface correctly.
Time Complexity:
Running time or the execution time of operations of data structure must be as small as
possible.
Space Complexity:
Memory usage of a data structure operation should be as little as possible.
Operations on Data Structures: The operations involve in data structure are as follows.
Create: Used to allocate/reserve memory for the data element(s).
Destroy: This operation deallocate/destroy the memory space assigned to the specified
data structure.
Selection: Accessing a particular data within a data structure.
Update: For updation (insertion or deletion) of data in the data structure.
Searching: Used to find out the presence of the specified data item in the list of data
Sorting: Process of arranging all data items either in ascending or in descending order.
Merging: Process of combining data items of two different sorted lists of data items into
a single list.
Stack
A stack is an ordered collection of items into which new items may be inserted and from which
items may be deleted at one end, called the TOP of the stack. It is a LIFO (Last In First Out) kind
of data structure.
Operations on Stack:
Push: Adds an item onto the stack. PUSH (s, i); Adds the item i to the top of stack.
Pop: Removes the most-recently-pushed item from the stack. POP (s); Removes the top element
and returns it as a function value.
Implementation of Stack: A stack can be implemented using two ways:
Array
Linked list.
Applications of Stack:
There are many applications of stack some of the important applications are given below.
Backtracking
Depth first Search
Function Calls:
Simulation of Recursive calls
Expression Evaluation:
Reversing a List
Expression conversion
Towers of Hanoi
Queue
It is a non-primitive, linear data structure in which elements are added/inserted at one end
(called the REAR) and elements are removed/deleted from the other end (called the
FRONT). A queue is logically a FIFO (First in First Out) type of list.
Operations on Queue:
Enqueue:
Adds an item onto the end of the queue ENQUEUE(Q, i); Adds the item i onto the end of
queue.
Dequeue:
Removes the item from the front of the queue. DEQUEUE (Q); Removes the first
element and returns it as a function value.
Queue Implementation: Queue can be implemented in two ways.
Static implementation (using arrays)
Dynamic implementation (using painters)
Queue types:
Circular Queue
Double ended Queue
Priority Queue
Applications of Queue:
Breadth first Search
CPU Scheduling
Routing Algorithms
Computation of shortest paths
Computation a cycle in the graph
Linked Lists
Linked list is a special data structure in which data elements are linked to one another. Here,
each element is called a node which has two parts
Operations on Linked Lists: The following operations involve in linked list are as given below
Creation
Insertion
Deletion
Traversing
Types of Linked Lists
Singly Linked List:
Doubly Linked List:
Circular Linked List:
Circular Doubly Linked List:
Trees
A tree can be defined as finite set of data
items called nodes. Tree is a nonlinear type of
data structure in which data items are
arranged in a sorted sequence. Trees
represent the hierarchical relationship
between various elements. The tree always
grown in length towards bottom in data
structure.
Graphs
A graph G (V, E) is a set of vertices V and a set of edge E. An edge connects a pair of
vertices. Vertices in the graph are shown as point or circle and edges are drawn as arcs or
line segment.
In Java, an ADT can be expressed by an interface, which is simply a list of method declarations,
where each method has an empty body. An ADT is recognized by a concrete data structure,
which is modeled in Java by a class. A class defines the data being stored and the operations
supported by the objects that are instances of the class. Also, unlike interfaces, classes specify
how the operations are performed in the body of each method.
Ex :
Stack ADT
interface stack
{
public Object pop();
public void push();
public Object peek();
public void display();
}
Advantages
Encapsulation:
The user does not need any technical knowledge of how the implementation works to use
the ADT. In this way, the implementation may be complex but will be encapsulated in a
simple interface when it is actually used.
Localization of change:
Code that uses an ADT object will not need to be edited if the implementation of the
ADT is changed, since any changes to the implementation must still comply with the
properties and abilities specified in the ADT definition.
Flexibility:
Different implementations of an ADT may be more efficient in different situations and it
is possible to use each in the situation where they are preferable. Hence this flexibility
increases the overall efficiency.
Implementation
Modern object-oriented languages, such as C++ and Java, support implementation of
ADT in the form of a class. You can use struct in C for the same.
The reference of the last node contains a special value called “NULL” reference denoted
by “ X” in the diagram signals the end of the list. The linked list also contains a first
pointer variable called “START” or “HEAD” which refer to the first node in the list . A
special case is the list that has no nodes, such list is called the “Null List” or “EmptyList”
and is denoted by null reference in the start variable.
Operations:
We can perform the following operations on the linked lists
1. Traversing the list
2. Inserting a new node
3. Deleting a node from the list
4. Counting the number of nodes.
What is a singly linked list? Write procedures for create, delete, insert
operations?
The singly linked list node consists of the information part and reference part which
refers to the next node.
To refer the entire list we have “START” or HEAD and to refer last node “END”
reference variable.
start=nptr;
if(start== null)
{
start = nptr;
end = nptr;
size++;
return;
}
c. If list is exist
end . link= nptr;
end = nptr;
3. Procedure to Delete at HEAD:
a. Check list is exist
Return;
If(start == end){
Start = null;
End= null;
Size--;
Size--;
Return;
b. // if list has only one element
If(start == end)
{
Start = null;
End= null;
Size--;
}
c. // if list has more than one element
Node temp = start;
While( temp.link! = end)
temp= temp.link;
temp.link=null;
end =temp;
size--;
5. Procedure to insert at position
a. Create a new node
Node nptr= new noe(v,null)
b. Read the position to insert
pos=n;
if( pos > size)
print “ can’t insert an element “
c. //pos in between start and end
Node temp= start;
pos= pos-1;
for (i=1; i<size; i++)
{
If(i==pos)
{
nptr . link = temp;
size++;
}
temp= temp . link;
}
6. To delete at position
a. If(start== null)
Print “list is empty “
b. If(pos> size)
Print “ position is out of range “;
Return;
c. node temp1, temp2;
temp1=start;
temp2= start;
for(i=1;i<size;i++)
{
if(i==pos)
{
temp2.link = temp1.link;
Size--;
return;
}
temp2=temp1;
temp1 temp1.link;
}
7. Display the list
a. If(start =null)
Print “ list is empty “
Return;
b. Node temp= start;
While(temp!=null)
{
/* Class linkedList */
class linkedList {
protected Node start;
protected Node end ;
public int size ;
public linkedList( ) /* Constructor */
{
start = null;
end = null;
size = 0;
}
public boolean isEmpty( ) /* Function to check if list is empty */
{
return start == null;
}
public int getSize( ) /* Function to get size of list */
{
return size;
}
public void insertAtStart(int val ) /* Function to insert an element at begining */
{
Node nptr = new Node(val, null);
size++ ;
if(start == null)
{
start = nptr;
end = start;
}
else
{
nptr.setLink(start);
start = nptr;
}
}
public void insertAtEnd(int val) /* Function to insert an element at end */
{
Node nptr = new Node(val,null);
size++ ;
if(start == null)
{
start = nptr;
end = start;
}
else
{
end.setLink(nptr);
end = nptr;
}
}
public void insertAtPos(int val , int pos) /* Function to insert an element at position */
{
Node nptr = new Node(val, null);
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size; i++)
{
if (i == pos)
{
Node tmp = ptr.getLink() ;
ptr.setLink(nptr);
nptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size++ ;
}
public void deleteAtPos(int pos) /* Function to delete an element at position */
{
if (pos == 1)
{
start = start.getLink();
size--;
return ;
}
if (pos == size)
{
Node s = start;
Node t = start;
while (s != end)
{
t = s;
s = s.getLink();
}
end = t;
end.setLink(null);
size --;
return;
}
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{
Node tmp = ptr.getLink();
tmp = tmp.getLink();
ptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size-- ;
}
public void display( ) /* Function to display elements */
{
System.out.print("\nSingly Linked List = ");
if (size == 0)
{
System.out.print("empty\n");
return;
}
if (start.getLink() == null)
{
System.out.println(start.getData() );
return;
}
Node ptr = start;
System.out.print(start.getData()+ "->");
ptr = start.getLink();
while (ptr != null)
{
System.out.print(ptr.getData()+ "->");
ptr = ptr.getLink();
}
}
}
public class SinglyLinkedList /* Class SinglyLinkedList */
{
public static void main(String[ ] args)
{
Scanner scan = new Scanner(System.in);
linkedList list = new linkedList( ); /* Creating object of class linkedList */
System.out.println("Singly Linked List Test\n");
char ch;
/* Perform list operations */
do
{
System.out.println("\nSingly Linked List Operations\n");
System.out.println("1. insert at begining");
System.out.println("2. insert at end");
System.out.println("3. insert at position");
System.out.println("4. delete at position");
System.out.println("5. check empty");
System.out.println("6. get size");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
case 5 :
System.out.println("Empty status = "+ list.isEmpty());
break;
case 6 :
System.out.println("Size = "+ list.getSize() +" \n");
break;
default :
System.out.println("Wrong Entry \n ");
}
list.display( ); /* Display List */
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next( ).charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}
next = n;
}
public void setLinkPrev(Node p) /* Function to set link to previous node */
{
prev = p;
}
public Node getLinkNext( ) /* Funtion to get link to next node */
{
return next;
}
public Node getLinkPrev( ) /* Function to get link to previous node */
{
return prev;
}
public void setData(int d) /* Function to set data to node */
{
data = d;
}
public int getData( ) { /* Function to get data from node */
return data;
}
}
class linkedList /* Class linkedList */
{
protected Node start;
protected Node end ;
public int size;
public linkedList( ) /* Constructor */
{
start = null;
end = null;
size = 0;
}
public boolean isEmpty( ) /* Function to check if list is empty */
{
return start == null;
}
public int getSize( ) /* Function to get size of list */
{
return size;
}
public void insertAtStart(int val) /* Function to insert element at begining */
{
Node nptr = new Node(val, null, null);
if(start == null)
{
start = nptr;
end = start;
}
else
{
start.setLinkPrev(nptr);
nptr.setLinkNext(start);
start = nptr;
}
size++;
}
public void insertAtEnd(int val) /* Function to insert element at end */
{
Node nptr = new Node(val, null, null);
if(start == null)
{
start = nptr;
end = start;
}
else
{
nptr.setLinkPrev(end);
end.setLinkNext(nptr);
end = nptr;
}
size++;
}
public void insertAtPos(int val , int pos) /* Function to insert element at position */
{
Node nptr = new Node(val, null, null);
if (pos == 1)
{
insertAtStart(val);
return;
}
Node ptr = start;
for (int i = 2; i <= size; i++)
{
if (i == pos)
{
Node tmp = ptr.getLinkNext();
ptr.setLinkNext(nptr);
nptr.setLinkPrev(ptr);
nptr.setLinkNext(tmp);
tmp.setLinkPrev(nptr);
}
ptr = ptr.getLinkNext();
}
size++ ;
}
public void deleteAtPos(int pos) /* Function to delete node at position */
{
if (pos == 1)
{
if (size == 1)
{
start = null;
end = null;
size = 0;
return;
}
start = start.getLinkNext();
start.setLinkPrev(null);
size--;
return ;
}
if (pos == size)
{
end = end.getLinkPrev();
end.setLinkNext(null);
size-- ;
}
Node ptr = start.getLinkNext();
for (int i = 2; i <= size; i++)
{
if (i == pos)
{
Node p = ptr.getLinkPrev();
Node n = ptr.getLinkNext();
p.setLinkNext(n);
n.setLinkPrev(p);
size-- ;
return;
}
ptr = ptr.getLinkNext();
}
}
public void display( ) /* Function to display status of list */
{
System.out.print("\nDoubly Linked List = ");
if (size == 0)
{
System.out.print("empty\n");
return;
}
if (start.getLinkNext() == null)
{
System.out.println(start.getData() );
return;
}
Node ptr = start;
System.out.print(start.getData()+ " <-> ");
ptr = start.getLinkNext();
while (ptr.getLinkNext() != null)
{
System.out.print(ptr.getData()+ " <-> ");
ptr = ptr.getLinkNext();
}
System.out.print(ptr.getData()+ "\n");
}
}
case 3 :
System.out.println("Enter integer element to insert");
int num = scan.nextInt() ;
System.out.println("Enter position");
int pos = scan.nextInt() ;
if (pos < 1 || pos > list.getSize() )
System.out.println("Invalid position\n");
else
list.insertAtPos(num, pos);
break;
case 4 :
System.out.println("Enter position");
int p = scan.nextInt() ;
if (p < 1 || p > list.getSize() )
System.out.println("Invalid position\n");
else
list.deleteAtPos(p);
break;
case 5 :
System.out.println("Empty status = "+ list.isEmpty());
break;
case 6 :
System.out.println("Size = "+ list.getSize() +" \n");
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
list.display( ); /* Display List */
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);
What is an array ? Explain algorithm for delete insert and search an element
in the array?
Array:
It is a linear data structure. It is a collection of finite set of similar data elements. An array
is finite because it contains only limited number of elements.
Ex:
An array of integers to store the age of all students in a class.
Int age[ ]= new int[50];
Index:
All the elements in an array can be referenced bya subscript like a[i] this subscript is
known as index. An index is always an integervalue starts from 0 and ends with size-1.
One dimensional array:
if only one subscript is required to reference all the elements in array then the array is
referred as one dimensional array.
b. Sorting
c. Searching.
d. Insertion.
e. Deletion.
f. Merging.
a. Traversing:
i= L // start from lower bound
while(i<=U)
{
Process( a[i] )
i=i+1; // move to the next location
}
b. Sorting
This operation if performed on array , will sort it in a specified order(ascending /
descending)
i= U //initialized to upper bound
while(i>= L)
{
j = L;
While(j < i)
{
if(a[i]>a[j+i]) //comparing the order of elements
swap(a[j],a[j+]) // not in order , swap them
j=j+1;
}
I=i-1;
}
c. Searching:
This operation is applied to search an element of interest in an array.
a. I=L, found=0, location=0
b. While(i<=u && found==0)
{
If(a[i]==KEY)
{
found=1;
location=i;
break;
}
else
i=i+1;
}
c. if(found==1)
print “ search is successful “
else
print “ search is not successful”
d. Insertion:
This operation is used to insert an element into an array provided that the array is
not full
1. i = U
2. while( i > LOCATION )
3. {
a[i]= a[i-1] // place the element in the next position
i=i-1;
}
4. A[LOCATION]=KEY; //put the element at the desired location
e. Deletion
This operation is used to delete a particular element from an array. The element
will be deleted by overwriting it with its subsequent element then is also to be
deleted.
1. i= searcharray(A, KEY)
if (i = = 0 )
non-zero values in the matrix. For example, consider a matrix of size 5 X 6 containing 6
number of non- zero values. This matrix can be represented as shown in the fig:
In above example matrix, there are only 6 non-zero elements ( those are 9, 8, 4, 2, 5 & 2)
and matrix size is 5 X 6. We represent this matrix as shown in the above image. Here the
first row in the right side table is filled with values 5, 6 & 6 which indicates that it is a
sparse matrix with 5 rows, 6 columns & 6 non-zero values. Second row is filled with 0, 4,
& 9 which indicates the value in the matrix at 0th row, 4th column is 9. In the same way
the remaining non-zero values also follows the similar pattern.
Linked Representation
In linked representation, we use linked list data structure to represent a sparse matrix. In
this linked list, we use two different nodes namely header node and element node.
Header node consists of three fields and element node consists of five fields as shown in
the image...
Consider the above same sparse matrix used in the Triplet representation. This sparse
matrix can be represented using linked representation as shown in the below image...
In above 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 it's
respective header node.