DSA - Unit2_Final_Updated
DSA - Unit2_Final_Updated
2
INTRODUCTION
3
Data Structure
• Data structure is a particular way of organizing,
storing and retrieving data, so that it can be used
efficiently.
• It is the structural representation of logical
relationships between elements of data.
4
Data Structure
5
Data Structure
6
Abstract Data Type
• ADT is a mathematical specification of the data, a list of
operations that can be carried out on that data.
• It includes the specification of what it does, but excludes the
specification of how it does. Operations on set ADT: Union,
Intersection, Size and Complement.
• The primary objective is to separate the implementation of
the abstract data types from their function.
• Three most common used abstract data types are Lists,
Stacks, and Queues.
7
Abstract Data Type
• Three most common used abstract data types are Lists,
Stacks, and Queues.
• ADT = Type + Functions+ Behavior of Each Function
• Benefits
• Code is easier to understand. Provides modularity and
reusability.
• Implementations of ADTs can be changed without requiring
changes to the program that uses the ADTs.
8
List ADT
• List is a linear collection of ordered elements.
• The general form of the list of size N is: A , A , …, A
0 1 N-1
9
List ADT
• Various operations performed on a List ADT
• Insert (X,5) - Insert the element X after the position 5.
• Delete (X) - The element X is deleted.
• Find (X) - Returns the position of X
• Next (i) - Returns the position of its successor
element i+1.
• Previous (i) - Returns the position of its predecessor
element i-1.
• PrintList - Displays the List contents.
• MakeEmpty - Makes the List empty.
10
List ADT
• Implementation of List ADT
• Array implementation
• Linked List implementation
• Cursor implementation
11
Array Implementation of List ADT
Array Implementation of List ADT
Array Implementation of List ADT
15
Linked List
• Linked list is a dynamic data structure which is an
ordered collection of homogeneous data elements
called nodes, in which each element contains two
parts: data or Info and one or more links.
• The data holds the application data to be processed.
The link contains (the pointer) the address of the
next element in the list.
Linked List
• A linked list is a linear collection of data elements.
These data elements are called nodes.
Linked List
• Why Linked List?
• Even though searching an array for an individual element can be very
efficient, array has some limitations. So arrays are generally not used
to implement Lists.
• Advantages of Linked List
• Linked list are dynamic data structures - The size is not fixed.
They can grow or shrink during the execution of a program.
• Efficient memory utilization - memory is not pre-allocated. Memory
is allocated, whenever it is required and it is de- allocated whenever it
is not needed. Data are stored in non-continuous memory blocks.
• Insertion and deletion of elements are easier and efficient.
Provides flexibility. No need to shift elements of a linked list to make
room for a new element or to delete an element.
• Disadvantages of Linked List
• More memory - Needs space for pointer (link field).
• Accessing arbitrary element is time consuming. Only sequential
search is supported not binary search.
Prepared By: L.Josephine Usha, AP/IT, SXCCE
Operations on Linked List
• Creation- This operation is used to create a linked list. Once a linked list is
created with one node, insertion operation can be used to add more elements in a
node.
• Insertion- This operation is used to insert a new node at any specified location in
the linked list. A new node may be inserted,
• At the beginning of the linked list,
• At the end of the linked list,
• At any specified position in between in a linked list.
• Deletion- This operation is used to delete an item (or node) from the linked list. A
node may be deleted from the,
• Beginning of a linked list,
• End of a linked list,
• Specified location of the linked list.
• Traversing - It is the process of going through all the nodes from one end to
another end of a linked list. In a singly linked list we can visit the nodes only from
left to right (forward traversing). But in doubly linked list forward and backward
traversing is possible.
• Searching- It is the process finding a specified node in a linked list.
• Concatenation- It is the process of appending the second list to the end of the
Linked List
• Types of linked list
• Singly linked list or Linear list or One-way list
• Doubly linked list or Two-way list
• Circular linked list
• Doubly circular linked list
Singly Linked List
• In singly linked list, each element (except the first one) has a
unique predecessor, and each element (except the last one)
has a unique successor.
• Each node contains two parts: data or Info and link.
• The data holds the application data to be processed. The link
contains the address of the next node in the list. That is, each
node has a single pointer to the next node. The last node
contains a NULL pointer indicating the end of the list.
Singly Linked List
• Sentinel Node
• It is also called as Header node or Dummy node.
• Advantages
• Sentinel node is used to solve the following problems
• First, there is no really obvious way to insert at the front of the
list from the definitions given.
• Second, deleting from the front of the list is a special case,
because it changes the start of the list; careless coding will lose
the list.
• A third problem concerns deletion in general. Although the pointer
moves above are simple, the deletion algorithm requires us to
keep track of the cell before the one that we want to delete.
• Disadvantages
• It consumes extra space.
Singly Linked List
• Insertion
• Creating a new node from empty List
Singly Linked List
• Insertion
• Inserting a node to the front of list
Singly Linked List
• Insertion
• Inserting a node in the middle
Singly Linked List
• Insertion
• Inserting a node to the end of list.
Singly Linked List
• Deletion
• Deleting a node to the front of list
Singly Linked List
• Deletion
• Deleting the middle node
Singly Linked List
• Deletion
• Deleting the last node
Singly Linked List
position TempCell,P;
while(P->next->next!=NULL)
P = P->next;
TempCell = P->next;
P->next = NULL;
free(TempCell);
}
Circular Linked List
• Definition
• A circular linked list is one, which has no beginning and no
end. Circular linked list is a list in which every node has a
successor; the "last" element is succeeded by the "first"
element. We can start at any node in the list and traverse
the entire list.
Circular Linked List
• Why circular linked list?
• With a singly linked list structure, given a pointer to a node anywhere in
the list, we can access all the nodes that follow but none of the nodes that
precede it. We must always have a pointer to the beginning of the list to
be able to access all the nodes in the list. In a circular linked list, every
node is accessible from a given node.
• In deletion of singly linked list, to find the predecessor requires that a
search be carried out by chaining through the nodes from the first node of
the list. But this requirement does not exist for a circular list, since the
search for the predecessor of node X can be initiated from X itself.
• Concatenation and splitting becomes more efficient.
Circular Linked List
• Disadvantages
• The circular linked list requires extra care to detect
the end of the list.
• It may be possible to get into an infinite loop. So it
needs a header node to indicate the start or end of
the list.
OPERATIONS ON CIRCULARLY LINKED LIST
•Insertion
•Deletion
•Display
temp=head;
temp->next = new;
new -> next = head;
Insertion in a Circular Linked List
Step 4 - If it is Not Empty then, define a Node pointer 'temp' and initialize with 'head‘
Step 5 - Keep moving the 'temp' to its next node until it reaches to the last node
(until 'temp → next == head').
Step 6 - Set 'newNode → next =head', 'head = newNode' and 'temp → next =
head'.
Inserting At the End of the list
• Steps to insert a new node at end of the circular linked list.
Step 3 - If it is Empty then, set head = newNode and newNode → next = head
Step 4 - If it is Not Empty then, define a node pointer temp and initialize
with head
Step 5 - Keep moving the temp to its next node until it reaches to the last node in
the list (until temp → next == head)
Step 3 - If it is Empty then, set head = newNode and newNode → next = head.
Step 4 - If it is Not Empty then, define a node pointer temp and initialize
with head
Step 5 - Keep moving the temp to its next node until it reaches to the node after which
we want to insert the newNode (until temp1 → data is equal to location, here
location is the node value after which we want to insert the newNode).
Inserting At Specific location in the list (After a Node)
Step 6 - Every time check whether temp is reached to the last node or not. If it is reached
to last node then display 'Given node is not found in the list!!!
Step 8 - If temp is last node then set temp → next = newNode and
Step 9 - If temp is not last node then set newNode → next = temp → next
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function
Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and
initialize both 'temp1' and 'temp2' with head
Step 4 - Check whether list is having only one node (temp1 → next == head)
Step 5 - If it is TRUE then set head = NULL and delete temp1 (Setting Empty list
conditions)
Step 6 - If it is FALSE move the temp1 until it reaches to the last node.
(until temp1 → next == head )
Step 7 - Then set head = temp2 → next, temp1 → next = head and
delete temp2
DELETING FROM END OF THE LIST
• The following steps to delete a node from end of the circular linked list.
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function.
Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and
initialize 'temp1' with head
Step 4 - Check whether list has only one Node (temp1 → next == head)
Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And terminate from the
function. (Setting Empty list condition)
Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to its next node. Repeat
the same until temp1 reaches to the last node in the list. (until temp1 → next ==
head)
• First position.
• Last Position.
• At any given position i.
Deleting the last node of the Circular Linked List
Deleting nodes at given index in the Circular
linked list
Doubly Linked List
• Doubly linked list is a linked list in which each node is
linked to both its successor and its predecessor. In a
doubly linked list, the nodes are linked in both
directions.
• Each node of a doubly linked list contains three parts:
• Info: the data stored in the node
• Next/FLink: the pointer to the following node.
• Back/BLink: the pointer to the preceding node
Doubly Linked List
Doubly Linked List
• Why doubly linked list?
• In singly linked list, it is difficult to perform traversing the list
in reverse.
• To delete a node, we need find its predecessor of that node.
• Advantages
• Traversing in reverse is possible.
• Deletion operation is easier, since it has pointers to its
predecessor and successor.
• Finding the predecessor and successor of a node is easier.
•They are also useful for other linked data which require “rewind” and “fast
forward” of the data
Doubly Linked
Lists
• Doubly linked lists
•Each node points to not only successor but the
predecessor
•There are two NULL: at the first and
last nodes in the list
•Advantage: given a node, it is easy to visit its predecessor.
Convenient to traverse lists backwards
Address of next
inf
node
o
NUL 13 6 12 NUL
L L
Address of
previous
node
Las
Hea
Doubly-linked
lists
head NUL
a b c L
last
tem Las
Deleting a node from the list
Struct node *delete(Struct node *head, int data) Else
{ {
Struct node *temp; printf(“Element %d not found \n”, data);
If(head==NULL) return head;
{ }
printf(“List is empty”); }
return head;
}
If(head->next==NULL) Time Complexity – O(1)
{
If(head->info==data)
{
temp=head;
head=NULL;
free(temp);
return head;
} tem
p
Hea 13 NUL
d L
NUL
L
Deletion of first
{
node
Struct node *delete(Struct node *head, int data)
Struct node *temp;
If(head==NULL)
{ •Time Complexity – O(1)
printf(“List is empty”);
return head;
}
If(head->info==data)
{
temp=head;
head=head->next;
head->previous=NULL;
free(temp);
return head;
}
Deletion of a node in the
middle
temp=head->next;
While(temp->next!=NULL)
{
If(temp->info==data)
{
temp->previous->next=temp->next;
temp->next->previous=temp->previous;
free(temp);
return head;
}
temp=temp->next;
}
13 12 8
6
NULL
Deletion of a node
at end
int deleteFromEnd()
{
struct node *temp;
temp = last;
if(temp->previous==NULL)
{
free(temp);
head=NULL;
last=NULL;
return 0;
}
printf("\nData deleted from list is %d \n",last->data);
last=temp->previous;
last->next=NULL;
free(temp);
return 0;
}
13 6 12
8
NULL
Advantages and Disadvantages of Doubly Linked List
• Advantages:
1.We can traverse in both directions i.e. from starting to end and as well as from end to
starting.
2. It is easy to reverse the linked list.
3.If we are at a node, then we can go to any node. But in linear linked list, it is not
possible to reach the previous node.
Disadvantages:
1.It requires more space per space per node because one extra field is required for pointer
to previous node.
2. Insertion and deletion take more time than linear linked list because more pointer
operations are required than linear linked list.
Review Questions
1) How do you calculate the pointer difference in a memory efficient double linked list?
a) head xor tail b) pointer to previous node xor pointer to next node
c) pointer to next node - pointer to previous node
d) pointer to previous node - pointer to next node
•The 2d array can be used to represent a sparse matrix in which there are
three rows named as:
• Row: It is an index of a row where a non-zero element is located.
•Column: It is an index of the column where a non-zero element is located.
•Value: The value of the non-zero ele
•Representing a sparse matrix by a 2D array leads to wastage of lots of
memory as zeroes in the matrix are of no use in most of the cases.
•So, instead of storing zeroes with non-zero elements, we only store non-
zero elements. T
•This means storing non-zero elements with triples- (Row, Column, value).
Sparse Matrix…
10
5
Application of Linked List
10
6
Applications of linked list in
computer science
•Implementation of stacks and queues
•Implementation of graphs : Adjacency list representation of graphs is
most popular which is uses linked list to store adjacent vertices.
•Dynamic memory allocation : We use linked list of free blocks.
•Maintaining directory of names
•Performing arithmetic operations on long integers
•Manipulation of polynomials by storing constants in the node of
linked list
•representing sparse matrices
10
7
Applications of linked list in
real world
• Image viewer – Previous and next images are linked, hence can be
accessed by next and previous button.
• Previous and next page in web browser – We can access previous and
next url searched in web browser by pressing back and next button
since, they are linked as linked list.
• Music Player – Songs in music player are linked to previous and next
song. you can play songs either from starting or ending of the list.
10
8
Polynomial Arithmetic using Linked List
10
9
•A polynomial p(x) is the expression in variable x which
is in the form (axn + bxn-1 + …. + jx+ k), where a, b, c
…., k fall in the category of real numbers and 'n' is non
negative integer, which is called the degree
polynomial.
of
•A polynomial can be thought of as an ordered list of
non zero terms. Each non zero term is a two-tuple
which holds two pieces of information:
•The exponent part
•The coefficient part
11
0
Adding two polynomials using
Linked List
Given two polynomial numbers represented by a linked list.
Write a function that add these lists means add the coefficients
who have same variable powers.
11
1
1. Applications of Circular List -Joseph
Problem
2. Doubly Linked List
Josephus Circle using circular linked list
• There are n people standing in a circle waiting to be executed. The counting out begins at
some point in the circle and proceeds around the circle in a fixed direction. In each step, a
certain number of people are skipped and the next person is executed. The elimination
proceeds around the circle (which is becoming smaller and smaller as the executed people
are removed), until only the last person remains, who is given freedom. Given the total
number of persons n and a number m which indicates that m-1 persons are skipped and m-th
person is killed in circle. The task is to choose the place in the initial circle so that you are the
last one remaining and so survive.
Example
Josephus Problem - Snippet
int josephus(int m, node *head)
{ f->next=head->next;
node *f; //sequence in which nodes getting deleted
int
c=1; printf("%d->",head->data);
while(h head=f->next;
ead- }
>next! printf("\n");
=head)
printf("Winner is:%d\n",head-
{
>data); return;
c=1
}
;
whi
le(c
!
=m
)
Exercise
•Write a C program to implement the following operations using
Circular Linked List
•Insertion in all the positions like start , middle and end
•Deletion in all the positions like start , middle and end
•Display
Quiz
1. Find the concept which is right for the below condition.“Any node can be a starting point.
We can traverse the whole list by starting from any point. We just need to stop when the
first visited node is visited again”.
• Circular Linked List
• Singly Linked List
• Stack
• Queue
2. What is the right statement (condition) to check the last node in the circular linked list.
(Assume temp is initialized as temp=head)
• temp->next=NULL
• temp->next=head
• temp=NULL
• temp=head
Quiz
3. Find the code used to count the nodes in the circular linked list.
Cursor Based
Implementation
Methodology
Motivation
• Some programming languages doesn’t support pointers.
• But we need linked list representation to store data.
• Solution:
• Cursor implementation – Linked list implementation using arrays.
What is Cursor
List?
•A CursorList is an array version of a Linked List.
•It is an array of list nodes but instead of each node containing a
pointer to the next item in the linked list, each node element in the
array contains the index for the next node element.
Methodolo
gy
•Convert a linked list based implementation to an array
based implementation.
• Instead of pointers, array index could be used to keep track of node.
•Convert the node structures (collection of data and next pointer) to a
global array of structures.
•Need to find a way to perform dynamic memory allocation performed
using malloc and free functions.
Initializing Cursor
Space
•Cursor_space[list] =0;
Cursor implementation of linked lists -
Example
return P;
}
Initializing Cursor
Space
•Cursor_space[list] =0;
Cursor implementation of linked lists -
Example
TmpCell = CursorAlloc( )
if( TmpCell ==0 )
fatal_error("Out of
space!!!");
CursorSpace[TmpCell].Element = x;
CursorSpace[TmpCell]. Next = CursorSpace[P]. Next;
CursorSpace[P]. Next =TmpCell;
}
Find
Routine
/* Return Position of X in L; 0 if not found */
/* Uses a header node */
P = CursorSpace[L].Next;
while( P && CursorSpace[P].Element != x )
P = CursorSpace[P].Next;
return P;
}
Deletion
Routine
/* Delete first occurrence of x from a list */
/* Assume use of a header node */
P = FindPrevious( x, L );
list. 4 5 9
5 7 0
4. Find the first 3 smallest element from the 6 - 8
linked list. 7 header 2
5. Remove duplicates from the given linked 8 - 10
list. 9 15 5
10 - 0
Review
1.
Questions
Why we need cursor implementation-> Implement linked list in programming language that do not support pointers
2. The cursor implementation is . Linked list implementation using arrays.
3. How to create linked list using cursor implementation-> Global Arrays of structures
4. Default list in cursor implementation is called .
Free list 0
5. The header of the free list is at location .
Value at next field of 0
6. Node to allocate and released node always occur at .
7. Condition to find the last node of the list . if(cursor[p].next == 0)