Module 2
Module 2
ALGRITHMS
Dr.S.T.Suganthi, AP-III/EEE
Department of Electrical and Electronics
Engineering
Module 2
What is Data Type
Two important things about data types:
Example:
Int A
- Takes only integer values
- Operations: addition, subtractions, multiplications,
bitwise operation etc.
User Defined Data Types
• In contrast to primitive data types, there is a concept of user
defined data types.
• The operations and values of user defined data types are not
specified in the language itself but is specified by the user.
• struct point {
int x;
int y;
};
Abstract Data Type (ADT)
• ADTs are like user defined data types which defines
operations on values using functions without specifying what
is there inside the function and how the operations are
performed.
• Operations:
push() – insert an element into the stack
pop() –delete an element from the stack
isEmpty() –Checks if stack is empty
isFull()- checks if stack is full
Abstract Data Types
List as Abstract data Type
int A[10];
A[i]=2;
print A[i];
List as Abstract data Type
9
Introduction to Linked Lists
10
Linked List
•A linked list is a data structure which allows to store data
dynamically and manage data efficiently.
•Typically, a linked list, in its simplest form looks like the following
header
A B C NULL
11
Linked List
•Few salient features
• There is a pointer (called header) points the first element (also
called node)
• Successive nodes are connected by pointers.
• Last element points to NULL.
• It can grow or shrink in size during execution of a program.
• It can be made just as long as required.
• It does not waste memory space, consume exactly what it needs.
12
Arrays versus Linked Lists
13
Array: Contagious Storage
arrayName
0 10
1 15
2 20
3 22
4 25
5 30
6 35
7 40
8 45
9 50
14
Array versus Linked Lists
•In arrays
• elements are stored in a contagious memory locations
15
Linked List: Non-Contagious Storage
h a i e c g
a
15 10 15 20 22 25 30
b f k b d
45
c
25 35 40 45 50
d
50
e
22 h
f 10 a 15 i 20 e 22 c 25 g 30 f
35
g
30
h 35 k 40 b 45 d 50
10
i
20 h
j
10 15 20 22 25 30
k
40
35 40 45 50
16
Array versus Linked Lists
•In Linked lists
• adjacency between any two elements are maintained by means of links or pointers
17
Linked Lists in C
18
Defining a Node of a Linked List
Each structure of the list is called a node, and consists of two fields:
• Item (or) data
• Address of the next item in the list (or) pointer to the next node in the
list
struct node
node
{
int data; /* Data */ Data
struct node *next; /* pointer*/ next
} ;
Note:
Such structures which contain a member field pointing to the same structure type are
called self-referential structures.
19
Types of Lists: Single Linked List
Depending on the way in which the links are used to maintain
adjacency, several different types of linked lists are possible.
head
A B C NULL
20
Types of Lists: Double Linked List
Double linked list
• Pointers exist between adjacent nodes in both directions.
• The list can be traversed either forward or backward.
• Usually two pointers are maintained to keep track of the list, head and
tail.
head tail
A B C
21
Defining a Node of a Double Linked List
Each node of doubly linked list (DLL) consists of three fields:
• Item (or) Data
• Pointer of the next node in DLL
• Pointer of the previous node in DLL
node
Data
prev next
22
Double Linked List
• Doubly linked list is a collection of nodes linked together in a sequential way.
• Doubly linked list is almost similar to singly linked list except it contains two
address or reference fields, where one of the address field contains reference of
the next node and other contains reference of the previous node.
• First and last node of a linked list contains a terminator generally a NULL
value, that determines the start and end of the list.
• Doubly linked list is sometimes also referred as bi-directional linked list since it
allows traversal of nodes in both direction.
• Since doubly linked list allows the traversal of nodes in both direction, we can
keep track of both first and last nodes.
23
Double versus Single Linked List
24
Types of Lists: Circular Linked List
head
A B C
25
Circular Linked List
• A circular linked list is basically a linear linked list that may be single- or
double-linked.
• The only difference is that there is no any NULL value terminating the list.
• In fact in the list every node points to the next node and last node points to the
first node, thus forming a circle. Since it forms a circle with no end to stop it is
called as circular linked list.
• In circular linked list there can be no starting or ending node, whole node can be
traversed from any node.
• In order to traverse the circular linked list, only once we need to traverse entire
list until the starting node is not traversed again.
• A circular linked list can be implemented using both singly linked list and
doubly linked list.
26
Example 1: Creating a Single Linked List
Linked list to store and print roll number, name and age of 3 students.
#include <stdio.h>
struct stud
{
int roll;
char name[30];
int age;
struct stud *next;
};
main()
{
struct stud n1, n2, n3;
struct stud *p;
scanf (“%d %s %d”, &n1.roll, n1.name, &n1.age);
scanf (“%d %s %d”, &n2.roll,n2.name, &n2.age);
scanf (“%d %s %d”, &n3.roll,n3.name, &n3.age);
27
Example 1: Creating a Single Linked List
n1.next = &n2 ;
n2.next = &n3 ;
n3.next = NULL ;
/* Now traverse the list and print the elements */
p = &n1 ; /* point to 1st element */
while (p != NULL)
{
printf (“\n %d %s %d”, p->roll, p->name, p->age);
p = p->next;
}
}
28
Example 1: Illustration
The structure:
struct stud
{
int roll;
char name[30];
int age;
struct stud *next;
};
Also assume the list with three nodes n1, n2 and n3 for 3 students.
29
Example 1: Illustration
To create the links between nodes, it is written as:
n1.next = &n2 ;
n2.next = &n3 ;
n3.next = NULL ; /* No more nodes follow */
roll
name
age
next NULL
n1 n2 n3
30
Creating a single linked list
If we need n number of nodes in the linked list:
• Allocate n newNodes, one by one.
• Read in the data for the newNodes.
• Modify the links of the newNodes so that the chain is formed.
It creates n number of nodes . For e.g. if the data entered is 200, 50, 30 then
the list look like
head
100 200 50 30 NULL
31
Example 3: Creating a Single Linked List
C-program to copy an array to a single linked list.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data; //Data part
struct node *next; //Address part
};
int main()
{
struct node *header, *newNode, *temp;
int data, i, n, a[100];
printf("Enter the total number of data: ");
scanf("%d", &n);
// Write code here to initialize the array a with n elements //
...
32
Example 2: Creating a Single Linked List
/* A node is created by allocating memory to a structure */
newNode = (struct node *)malloc(sizeof(struct node));
33
Example 2: Creating a Single Linked List
for(i = 1; i <= n; i++)
{
/* A newNode is created by allocating memory */
newNode = (struct node *)malloc(sizeof(struct node));
if(newNode == NULL)
{
printf("Unable to allocate memory.");
break;
}
else
{
newNode->data = a[i]; //Links the data field of newNode with a[i]
newNode->next = NULL; //Links the address field of newNode with NULL
34
Operations on Linked Lists
35
Operations on single linked list
• Traversing a list
• Printing, finding minimum, etc.
37
Single Linked List: Traversing
39
Insertion in a Linked List
40
Single Linked List: Insertion
Insertion steps:
• Create a new node
• Start from the header node
• Manage links to
• Insert at front
• Insert at end
• Insert at any position
41
Insertion at Front
42
Insertion at Front
Step 2: Link the newly created node with the head node, i.e. the newNode will now
point to head node.
Step 3: Make the new node as the head node, i.e. now head node will point to newNode.
43
Insertion at front
/*Create a new node and insert at the beginning of the linked list.*/
if(newNode == NULL)
{
printf("Unable to allocate memory.");
}
else
{
newNode->data = data; //Links the data part
newNode->next = head; //Links the address part
44
Single Linked List: Insertion at End
Step 2: Traverse to the last node of the linked list and connect the last node of the list with
the new node, i.e. last node will now point to new node. (lastNode->next =
newNode).
45
Insertion at End
/* Create a new node and insert at the end of the linked list. */
void insertNodeAtEnd(int data)
{
struct node *newNode, *temp;
newNode = (struct node*)malloc(sizeof(struct node));
if(newNode == NULL)
{
printf("Unable to allocate memory.");
}
else
{
newNode->data = data; //Links the data part
newNode->next = NULL;
temp = head;
46
Single Linked List: Insertion at any Position
Steps to insert node at any position of Singly Linked List
Step 1: Create a new node.
Step 2: Traverse to the n-1th position of the linked list and connect the new node with the
n+1th node. (newNode->next = temp->next) where temp is the n-1th node.
47
Single Linked List: Insertion at any position
Step 3: Now at last connect the n-1th node with the new node i.e. the n-1th node will now
point to new node. (temp->next = newNode) where temp is the n-1th node.
48
Insertion at any Position
if(newNode == NULL)
{
printf("Unable to allocate memory.");
}
else
{
newNode->data = data; //Links the data part
newNode->next = NULL;
temp = head;
49
Insertion at any Position
if(temp == NULL)
break;
}
if(temp != NULL)
{
/* Links the address part of new node */
newNode->next = temp->next;
50
Double Linked List: Insertion at any Position
Steps to insert a new node at nth position in a Doubly linked list.
Step 1: Traverse to N-1 node in the list, where N is the position to insert. Say temp now
points to N-1th node.
Step 2: Create a newNode that is to be inserted and assign some data to its data field.
51
Doubly Linked List: Insertion at any Position
Step 3: Connect the next address field of newNode with the node pointed by next address
field of temp node.
Step 4: Connect the previous address field of newNode with the temp node.
52
Doubly Linked List: Insertion at any Position
Step 5: Check if temp.next is not NULL then, connect the previous address field of node
pointed by temp.next to newNode.
53
Doubly Linked List: Insertion at any Position
Step 7: Final doubly linked list looks like
54
Doubly Linked List: Insertion at any Position
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, data;
head = NULL;
last = NULL;
55
Doubly Linked List: Insertion at any Position
void createList(int n)
{
int i, data;
struct node *newNode;
if(n >= 1){ /* Creates and links the head node */
head = (struct node *)malloc(sizeof(struct node));
printf("Enter data of 1 node: ");
scanf("%d", &data);
head->data = data;
head->prev = NULL;
head->next = NULL;
last = head;
for(i=2; i<=n; i++){ /* Creates and links rest of the n-1 nodes */
newNode = (struct node *)malloc(sizeof(struct node));
printf("Enter data of %d node: ", i);
scanf("%d", &data);
newNode->data = data;
newNode->prev = last; //Links new node with the previous node
newNode->next = NULL;
56
Doubly Linked List: Insertion at any Position
void insert_position(int data, int position)
{
struct node * newNode, *temp;
if(head == NULL){
printf("Error, List is empty!\n");
}
else{
temp = head;
if(temp!=NULL){
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = temp->next; //Connects new node with n+1th node
newNode->prev = temp; //Connects new node with n-1th node
if(temp->next != NULL)
{
temp->next->prev = newNode; /* Connects n+1th node with new node */
}
temp->next = newNode; /* Connects n-1th node with new node */
printf("NODE INSERTED SUCCESSFULLY AT %d POSITION\n", position);
}
else{
printf("Error, Invalid position\n");
}
}
}
57
Doubly Linked List: Insertion at any Position
void displayList()
{
struct node * temp;
int n = 1;
if(head == NULL)
{
printf("List is empty.\n");
}
else
{
temp = head;
printf("DATA IN THE LIST:\n");
while(temp != NULL)
{
printf("DATA of %d node = %d\n", n, temp->data);
n++;
58
Few Exercises to Try Out
For doubly linked list write a function to:
• Insert a node at front of the list and at end of the list.
insert_front(data);
insert_end(data);
59
Deletion from a Linked List
60
Single Linked List: Deletion
Deletion steps
• Start from the header node
• Manage links to
• Delete at front
• Delete at end
• Delete at any position
• freeingup the node as free space.
61
Free Memory after Deletion
• Do not forget to free() memory location dynamically allocated
for a node after deletion of that node.
62
Single Linked List: Deletion at Front
Steps to delete first node of Singly Linked List
Step 1: Copy the address of first node i.e. head node to some temp variable say toDelete.
Step 2: Move the head to the second node of the linked list (head = head->next).
63
Single linked list: Deletion at front
Step 3: Disconnect the connection of first node to second node.
64
Deletion at Front
if(head == NULL)
{
printf("List is already empty.");
}
else
{
toDelete = head;
head = head->next;
65
Single linked list: Deletion at End
Steps to delete last node of a Singly Linked List
Step 1: Traverse to the last node of the linked list keeping track of the second last node in
some temp variable say secondLastNode.
Step 2: If the last node is the head node then make the head node as NULL else disconnect
the second last node with the last node i.e. secondLastNode->next = NULL
66
Single linked list: Deletion at End
Step 3: Free the memory occupied by the last node.
67
Deletion at End
68
Single Linked List: Deletion at any Position
Steps to delete a node at any position of Singly Linked List
Step 1: Traverse to the nth node of the singly linked list and also keep reference of n-1 th node
in some temp variable say prevNode.
Step 2: Reconnect n-1th node with the n+1th node i.e. prevNode->next = toDelete->next
(Where prevNode is n-1th node and toDelete node is the nth node and toDelete->next is the n+1th
node).
69
Single Linked List: Deletion at any Position
Step 3: Free the memory occupied by the nth node i.e. toDelete node.
70
Deletion at any Position
if(toDelete == NULL)
break;
}
71
Deletion at any Position
if(toDelete != NULL)
{
if(toDelete == head)
head = head->next;
prevNode->next = toDelete->next;
toDelete->next = NULL;
72
Circular linked list:
Basic structure of singly circular linked list:
73
Circular linked list:
Advantages of a Circular linked list
• Entire list can be traversed from any node.
• Circular lists are the required data structure when we want a list to be accessed in a circle or
loop.
• Despite of being singly circular linked list we can easily traverse to its previous node,
which is not possible in singly linked list.
74
Operations on circular linked list
• Creation of list
• Traversal of list
• Insertion of node
• At the beginning of list
• At any position in the list
• Deletion of node
• Deletion of first node
• Deletion of node from middle of the list
• Deletion of last node
• Counting total number of nodes
• Reversing of list
75
Creation and Traversal of a Circular List
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node * next;
}*head;
int main()
{
int n, data;
head = NULL;
return 0;
}
76
Circular Linked List: Creation of List
void createList(int n)
{
int i, data;
struct node *prevNode, *newNode;
if(n >= 1){ /* Creates and links the head node */
head = (struct node *)malloc(sizeof(struct node));
head->data = data;
head->next = NULL;
prevNode = head;
for(i=2; i<=n; i++){ /* Creates and links rest of the n-1 nodes */
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = NULL;
prevNode->next = newNode; //Links the previous node with newly created node
prevNode = newNode; //Moves the previous node ahead
}
prevNode->next = head; //Links the last node with first node
printf("\nCIRCULAR LINKED LIST CREATED SUCCESSFULLY\n");
}
}
77
Circular Linked List: Traversal of List
void displayList()
{
struct node *current;
int n = 1;
if(head == NULL)
{
printf("List is empty.\n");
}
else
{
current = head;
printf("DATA IN THE LIST:\n");
do {
printf("Data %d = %d\n", n, current->data);
current = current->next;
n++;
}while(current != head);
}
}
78
Few Exercises to Try Out
For circular linked list write a function to:
• Insert a node at any position of the list and delete from the
beginning of the list.
insert_position(data,position);
delete_front();
79
Queues
Queue
Circular Queue
Double-ended Queue (Deque)
Priority Queue
DEFINITION
• A queue is a linear list in which it contains an ordered collection
of data items in which data can only be inserted at one end, called
the rear, and deleted from the other end, called the front.
• These restrictions ensure that the data is processed through the
queue in the order in which it is received.
• FIRST-COME-FIRST-SERVE basis(FCFS) OR FIRST IN,
FIRST OUT basics (FIFO) structure.
Primary queue operations:
Enqueue
Insert an element at the rear of the queue
Dequeue
Remove an element from the front of the queue
Remove Insert
(Dequeue) front rear (Enqueue)
IMPLEMENTATION:
To delete an element
The Queue[Front] is returned
the front pointer is incremented by 1
INITIALIZE THE QUEUE
items[SIZE-1]
. .
. .
. .
items[2]
items[1]
items[0] Front=0
Rear=-1
an item (1) is inserted at the Rear of the queue
items[size-1]
. .
. .
items[3]
items[2]
items[1]
items[0] 1 Front=0, Rear=0
A new item (2) is inserted at the Rear of the queue
items[SIZE-1]
. .
. .
items[3]
items[2]
items[1] 2 Rear=1
items[0] 1 Front=0
A new item (3) is inserted at the Rear of the queue
items[SIZE-1]
. .
. .
items[3]
items[2] 3 Rear=2
items[1] 2
items[0] 1 Front=0
A new item (4) is inserted at the Rear of
the queue
items[SIZE-1]
. .
. .
items[3] 4 Rear=3
items[2] 3
items[1] 2
items[0] 1 Front=0
Main()
#include<stdio.h> printf("\n Enter your choice:");
#include<conio.h> scanf("%d",&ch);
#define max 10 switch(ch)
void enqueue(); {
void dequeue(); case 1:
void display(); enqueue();
int rear= -1,front break;
=0,queue[max]; case 2:
void main() dequeue();
{ break;
int ch; case 3:
clrscr(); display();
do break;
{ case 4:
printf("\n 1.enqueue \n exit(0);
2.dequeue \n 3.display \n }
4.exit"); }
while(ch!=4);
getch();
}
Enqueue
Void enqueue()
{
if(rear>=max-1)
printf("\n Queue is Full \n");
else
{
printf("\n Enter the element to insert:");
scanf("%d",&x);
rear=rear+1;
queue[rear]=x;
}
DEQUEUE (OR) REMOVE
An item (1) is removed (deleted) from the Front of the
queue
items[SIZE-1]
. .
. .
items[3] 4 Rear=3
items[2] 3
items[1] 2 Front=1
items[0] 1
An item (2) is removed (deleted) from the Front of the
queue
items[SIZE-1]
. .
. .
items[3] 4 Rear=3
items[2] 3 Front=2
items[1] 2
items[0] 1
An item (3) is removed (deleted) from the Front of the queue
items[SIZE-1]
. .
. .
items[3] 4 Front=Rear=3
items[2] 3
items[1] 2
items[0] 1
An item (4) is removed (deleted) from the Front of the
queue
items[SIZE-1]
. .
items[4]
items[3] 4
items[2] 3
items[1] 2
items[0] 1 Front=0
Rear=-1
DEQUEUE
void dequeue()
{
if(front>rear)
printf("Queue is empty..\n");
else
{
if(front==rear)
{
printf("Element %d is dequed from the queue",queue[front]);
front=0;
rear=-1;
}
else
{
printf("Element %d is dequed from the queue",queue[front]);
front=front+1;
}}}
Display
void display()
{
int i;
if(front>rear)
printf("\n Queue is empty..\
n");
else
{
printf("\n Elements in the
queue :");
for(i=front;i<=rear;i++)
printf("%d\t",queue[i]);
}
}
INSERT / REMOVE ITEMS
.
. 5
items[3] 4 front=3
items[2] 3
items[1] 2
items[0] 1
Since all the items in the queue are required to shift when an item is
deleted, this method is not preferred.
The other method is circular queue.
When rear = MAXQUEUE-1, the next element is entered at items[0]
in case that spot is free.
Queue – Linked List -Initialization part
struct node
{
int data;
struct node*next;
}*front=NULL,*rear=NULL,*newnode;
ENQUEUE – LINKED LIST
void insert() else
{ {
int x;
newnode->data=x;
printf("\n\n Enter the item:");
scanf("%d",&x); newnode-
newnode=(struct >next=NULL;
node*)malloc(sizeof(struct rear->next=newnode;
node)); rear=newnode;
if(rear==NULL) }
{
}
newnode->data=x;
newnode->next=NULL;
front=newnode;
rear=newnode; }
DEQUEUE – LINKED LIST
else
void delet() {
{ temp=front;
int x; if(front==NULL)
struct node*temp; {
if(front==NULL) rear=NULL;
{ }
x=front->data;
printf("\n Queue is front=front->next;
empty...."); free(temp);
} printf("\n element deleted
is %d",x);
}}
DISPLAY – Linked
void display()
{
struct node*temp=front;
if(rear==NULL)
printf("\n\n Queue is empty..\n");
else
{
printf("\n\nThe elements in the Queue are :\t");
while(temp!=NULL)
{
printf("%d\t",temp->data);
temp=temp->next;
}
}
}
Circular Queue
• To solve this problem, queues implement wrapping around. Such
queues are called Circular Queues.
• Both the front and the rear pointers wrap around to the beginning of
the array.
• It is also called as “Ring buffer”.
• Items can inserted and deleted from a queue in O(1) time.
Example
qback qfront qback qback qback
D
A
C
C B C B C
qfront qfront qfront
Insert elem ents A,B, C Rem ove elem ent A Rem ove elem ent B Insert elem ent D,
D
qback
D E
C D E C D