0% found this document useful (0 votes)
14 views

Unit 1

Data Structure

Uploaded by

Dr. S.K. Sajan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Unit 1

Data Structure

Uploaded by

Dr. S.K. Sajan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

UNIT-I (Data Structure and Algorithms)

Data:
A collection of facts, concepts, figures, observations, occurrences or instructions in a formalized
manner.
Information:
The meaning that is currently assigned to data by means of the conventions applied to those data
(i.e. processed data)
Record:
Collection of related fields.
Data type:
Set of elements that share common set of properties used to solve a program.
Data Structures:
Data Structure is the way of organizing, storing, and retrieving data and their relationship with
each other.

Characteristics of data structures:


1. It depicts the logical representation of data in computer memory.
2. It represents the logical relationship between the various data elements.
3. It helps in efficient manipulation of stored data elements.
4. It allows the programs to process the data in an efficient manner.

1
Operations on Data Structures:
1. Traversal
2. Search
3. Insertion
4. Deletion

Primary Data Structures / Primitive Data Structures:


Primitive data structures include all the fundamental data structures that can be directly
manipulated by machine-level instructions. Some of the common primitive data structures
include integer, character, real, Boolean etc.

Secondary Data Structures/Non Primitive Data Structures:


Non primitive data structures, refer to all those data structures that are derived from one or more
primitive data structures. The objective of creating non-primitive data structures is to form sets
of homogeneous or heterogeneous data elements.

Linear Data Structures:


Linear data structures are data structures in which, all the data elements are arranged in linear or
sequential fashion. Examples of data structures include arrays, stacks, queues, linked lists, etc.

2
Non Linear Structures:
In non-linear data structures, there is definite order or sequence in which data elements are
arranged. For instance, a non-linear data structures could arrange data elements in a hierarchical
fashion. Examples of non-linear data structures are trees and graphs.

Static and dynamic data structure:


Static Ds:
If a ds is created using static memory allocation, ie. ds formed when the number of data
items are known in advance, it is known as static data static ds or fixed size ds.
Dynamic Ds:
If the ds is created using dynamic memory allocation i.e ds formed when the number of
data items are not known in advance is known as dynamic ds or variable size ds.

Application of data structures:


 Data structures are widely applied in the following areas:
 Compiler design
 Operating system
 Statistical analysis package
 DBMS
 Numerical analysis
 Simulation
 Artificial intelligence
 Graphics

ABSTRACT DATA TYPES (ADTS):


An abstract Data type (ADT) is defined as a mathematical model with a collection of operations
defined on that model. Set of integers, together with the operations of union, intersection and set
difference form an example of an ADT. An ADT consists of data together with functions that
operate on that data.
Advantages/Benefits of ADT:
1. Modularity
2. Reuse
3
3. Code is easier to understand
4. Implementation of ADTs can be changed without requiring changes to the program
that uses the ADTs.

THE LIST ADT:


List is an ordered set of elements.
The general form of the list is A1, A2… AN
A1 - First element of the list
A2- 1st element of the list
N –Size of the list
If the element at position i is Ai, then its successor is Ai+1 and its predecessor is Ai-1

Implementation of list ADT:


1. Array based Implementation
2. Linked List based implementation

Array Implementation of list:


Array is a collection of specific number of same type of data stored in consecutive
memory locations. Array is a static data structure i.e., the memory should be allocated in advance
and the size is fixed. This will waste the memory space when used space is less than the
allocated space. Insertion and Deletion operation are expensive as it requires more data
movements.

4
The basic operations performed on a list of elements are
a. Creation of List.
b. Insertion of data in the List
c. Deletion of data from the List
d. Display all data’s in the List
e. Searching for a data in the list

Declaration of Array:
#define maxsize 10
int list[maxsize], n ;

Create Operation:
Create operation is used to create the list with „ n „ number of elements .If „ n „ exceeds
the array‟s maxsize, then elements cannot be inserted into the list. Otherwise the array
elements are stored in the consecutive array locations (i.e.) list [0], list [1] and so on.
void Create ( )
{
int i;
printf("\nEnter the number of elements to be added in the list:\t");
scanf("%d",&n);
printf("\nEnter the array elements:\t");
for(i=0;i<n;i++)
scanf("%d",&list[i]);
}

5
Insert Operation:
Insert operation is used to insert an element at particular position in the existing list. Inserting the
element in the last position of an array is easy. But inserting the element at a particular position
in an array is quite difficult since it involves all the subsequent elements to be shifted one
position to the right.

Routine to insert an element in the array:

Void Insert ( )
{
int i, data, pos;
printf("\nEnter the data to be inserted:\t");
scanf("%d",&data);
printf("\nEnter the position at which element to be inserted:\t");
scanf("%d",&pos);
if (pos==n)
printf (“Array overflow”);
for(i = n-1 ; i >= pos-1 ; i--)
list[i+1] = list[i];
list[pos-1] = data;
n=n+1;
Display();
}

6
7
8
Advantages of array implementation:
1. The elements are faster to access using random access
2. Searching an element is easier

Limitation of array implementation


Arrays store its nodes in consecutive memory locations.
 The number of elements in the array is fixed and it is not possible to change the number
of elements.
 Insertion and deletion operation in array are expensive. Since insertion is performed by
pushing the entire array one position down and deletion is performed by shifting the
entire array one position up.

Applications of arrays:
Arrays are particularly used in programs that require storing large collection of similar type data
elements.
9
10
11
1. SINGLY LINKED LIST

12
13
Inserting a New Node in a Linked List
How a new node is added into an already existing linked list. We will take four cases and then
see how insertion is done in each case.
Case 1: The new node is inserted at the beginning.
Case 2: The new node is inserted at the end.
Case 3: The new node is inserted after a given node.
Case 4: The new node is inserted before a given node.

OVERFLOW
Overflow is a condition that occurs when AVAIL = NULL or no free memory cell is present in
the system. When this condition occurs, the program must give an appropriate message.

Algorithm to insert a new node at the beginning

14
In Step 1, we first check whether memory is available for the new node. If the free memory
has exhausted, then an OVERFLOW message is printed. 
Otherwise, if a free memory cell is available, then we allocate space for the new node. Set its
DATA part with the given VAL and the next part is initialized with the address of the first
node of the list, which is stored in START. 
Now, since the new node is added as the first node of the list, it will now be known as the
START node, that is, the START pointer variable will now hold the address of the
NEW_NODE.

Note the following two steps: 


Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL -> NEXT 
These steps allocate memory for the new node. In C, there are functions like malloc(), alloc, and
calloc() which automatically do the memory allocation on behalf of the user.

Case 2: Inserting a Node at the End of a Linked List

15
Case 3: Inserting a Node after a Given Node in a Linked List

Case 4: Inserting a Node before a Given Node in a Linked List

Deleting a Node from a Linked List


We will discuss how a node is deleted from an already existing linked list. We will
consider three cases and then see how deletion is done in each case.

16
Case 1: The first node is deleted.
Case 2: The last node is deleted.
Case 3: The node after a given node is deleted.

Underflow is a condition that occurs when we try to delete a node from a linked list that is
empty. This happens when START = NULL or when there are no more nodes to delete. 
Note that when we delete a node from a linked list, we actually have to free the memory
occupied by that node. 
The memory is returned to the free pool so that it can be used to store other programs and 
data.
Whatever be the case of deletion, we always change

Algorithmic steps to delete a linked list node at a given position:


1. Input: A pointer to the head node of the linked list and the value to be deleted.
2. If the linked list is empty, return NULL.
3. If the node to be deleted is the head node, set the head node to the next node and delete the
original head node.
4. Otherwise, traverse the linked list from the head node until the node to be deleted is found.
5. If the node to be deleted is not found, return NULL.
6. Otherwise, set the previous node’s next pointer to the node after the node to be deleted.
7. Delete the node to be deleted.
8. Return the head node of the linked list.

Merging Two Sorted Linked Lists


Merging two sorted linked lists involves combining them into a new sorted linked list. Unlike
arrays, there is no need for an auxiliary array. We can achieve this efficiently using two extra
pointers: third, which points to the start node of the merged linked list, and last, which points to
the last node.
17
Algorithm
1. Initialize three pointers, first, second, and third, to the heads of the two sorted linked lists and

the merged list, respectively.

2. Create a pointer last and set it to NULL. This will keep track of the last node in the merged

list.

3. Iterate over the nodes of both linked lists until either of them becomes NULL. Inside the

loop, compare the data of the current nodes pointed by first and second

- If the data of the node in the first list is smaller, append it to the merged list

- If the data of the node in the second list is smaller or equal, append it to the merged list

- Update last to point to the last node in the merged list

- Move the pointer in the list whose node was appended

4. After the loop, check if there are remaining nodes in either of the two lists. If yes, append the

remaining nodes to the merged list.

5. The merged list is now complete.

18
A doubly linked list is a more complex data structure than a singly linked list, but it
offers several advantages. The main advantage of a doubly linked list is that it allows for
efficient traversal of the list in both directions. This is because each node in the list contains a
pointer to the previous node and a pointer to the next node. This allows for quick and easy
insertion and deletion of nodes from the list, as well as efficient traversal of the list in both
directions.

Representation of Doubly Linked List in Data Structure:


In a data structure, a doubly linked list is represented using nodes that have three fields:
1. Data
2. A pointer to the next node (next)
3. A pointer to the previous node (prev).

19
Node Definition:
Here is how a node in a Doubly Linked List is typically represented:

struct Node {

// To store the Value or data.


int data;

// Pointer to point the Previous Element


Node* prev;

// Pointer to point the Next Element


Node* next;
};

Each node in a Doubly Linked List contains the data it holds, a pointer to the next node
in the list, and a pointer to the previous node in the list. By linking these nodes together
through the next and prev pointers, we can traverse the list in both directions (forward and
backward), which is a key feature of a Doubly Linked List.

Operations on Doubly Linked List:


 Traversal in Doubly Linked List
 Searching in Doubly Linked List
 Finding Length of Doubly Linked List
 Insertion in Doubly Linked List:
o Insertion at the beginning of Doubly Linked List
o Insertion at the end of the Doubly Linked List
o Insertion at a specific position in Doubly Linked List
 Deletion in Doubly Linked List:
o Deletion of a node at the beginning of Doubly Linked List
o Deletion of a node at the end of Doubly Linked List
o Deletion of a node at a specific position in Doubly Linked List

20
Traversal in Doubly Linked List:
To Traverse the doubly list, we can use the following steps:
a. Forward Traversal:
 Initialize a pointer to the head of the linked list.
 While the pointer is not null:
 Visit the data at the current node.
 Move the pointer to the next node.
b. Backward Traversal:
 Initialize a pointer to the tail of the linked list.
 While the pointer is not null:
 Visit the data at the current node.
 Move the pointer to the previous node.

3. Circular Linked List


The circular linked list is a linked list where all nodes are connected to form a circle.
In a circular linked list, the first node and the last node are connected to each other which
forms a circle. There is no NULL at the end.

There are generally two types of circular linked lists:


 Circular singly linked list: In a circular Singly linked list, the last node of the list contains
a pointer to the first node of the list. We traverse the circular singly linked list until we
reach the same node where we started. The circular singly linked list has no beginning or
end. No null value is present in the next part of any of the nodes.

21
Representation of Circular singly linked list

 Circular Doubly linked list: Circular Doubly Linked List has properties of both doubly
linked list and circular linked list in which two consecutive elements are linked or
connected by the previous and next pointer and the last node points to the first node by the
next pointer and also the first node points to the last node by the previous pointer.

Representation of circular doubly linked list

Note: We will be using the singly circular linked list to represent the working of the circular
linked list.

Representation of circular linked list:


Circular linked lists are similar to single Linked Lists with the exception of connecting
the last node to the first node.

Node representation of a Circular Linked List:


// Class Node, similar to the linked list
class Node{
int value;

// Points to the next node.


Node next;
}

22
Applications of Linked lists
o Polynomial Manipulation representation
o Addition of long positive integers
o Representation of sparse matrices
o Addition of long positive integers
o Symbol table creation
o Mailing list
o Memory management
o Linked allocation of files
o Multiple precision arithmetic etc

Polynomial Manipulation
Polynomial manipulations are one of the most important applications of linked lists.
Polynomials are an important part of mathematics not inherently supported as a data type by
most languages. A polynomial is a collection of different terms, each comprising coefficients,
and exponents. It can be represented using a linked list. This representation makes polynomial
manipulation efficient.

While representing a polynomial using a linked list, each polynomial term represents a
node in the linked list. To get better efficiency in processing, we assume that the term of every
polynomial is stored within the linked list in the order of decreasing exponents. Also, no two
terms have the same exponent, and no term has a zero coefficient and without coefficients. The
coefficient takes a value of 1.

Each node of a linked list representing polynomial constitutes three parts:

o The first part contains the value of the coefficient of the term.
o The second part contains the value of the exponent.
o The third part, LINK points to the next term (next node).

23
The structure of a node of a linked list that represents a polynomial is shown below:

Consider a polynomial P(x) = 7x4 + 15x3 - 2 x2 + 9. Here 7, 15, -2, and 9 are the coefficients, and
4,3,2,0 are the exponents of the terms in the polynomial. On representing this polynomial using a
linked list, we have

Observe that the number of nodes equals the number of terms in the polynomial. So we
have 4 nodes. Moreover, the terms are stored to decrease exponents in the linked list. Such
representation of polynomial using linked lists makes the operations like subtraction, addition,
multiplication, etc., on polynomial very easy.

Declaration for Linked list implementation of Polynomial ADT

struct poly
{
int coeff;
int power;
struct poly *next;
}*list1,*list2,*list3;

24
Creation of the Polynomial
poly create(poly*head1,poly*newnode1)
{
poly *ptr;
if (head1==NULL)
{
}
else
{
}
head1=newnode1;
return (head1);
ptr=head1;
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=newnode1;
return(head1);
}

Addition of two polynomials


void add()
{
poly *ptr1, *ptr2, *newnode ;
ptr1= list1;
ptr2 = list2;
while( ptr1 != NULL && ptr2 != NULL )
{
newnode = (struct poly*)malloc( sizeof ( struct poly ));
if( ptr1 -> power = = ptr2 -> power )

25
{
newnode -> coeff = ptr1 -> coeff + ptr2 -> coeff;
newnode -> power = ptr1 -> power ;
newnode -> next = NULL;
list3 = create( list3, newnode );
ptr1 = ptr1 -> next;
ptr2 = ptr2 -> next;
}
else if(ptr1 -> power > ptr2 -> power )
{
}
else
{
ptr2 = ptr2 -> next;
}}}
newnode -> coeff = ptr1 -> coeff;
newnode -> power = ptr1 -> power;
newnode -> next = NULL;
list3 = create( list3, newnode );
ptr1 = ptr1 -> next;
newnode -> coeff = ptr2 -> coeff;
newnode -> power = ptr2 -> power;
newnode -> next = NULL;
list3 = create( list3, newnode );
ptr2 = ptr2 -> next;
}}}

26

You might also like