Professional Documents
Culture Documents
Following are the important terms to understand the concept of Linked List.
Link − Each link of a linked list can store a data called an element.
Next − Each link of a linked list contains a link to the next link called Next.
LinkedList − A Linked List contains the connection link to the first link called First.
Basic Terminology:
A linked list can be perceived as a sequence of nodes in which each node contains one or more data fields and a
pointer to the next node.
We can see a linked list in which every node contains two parts, an integer, and a pointer to the next node.
The last node will have no next node connected to it, so it will store a special value called NULL.
Since in a linked list, every node contains a pointer to another node which is of the same type, it is also called a self-
referential data type.
The starting point of the linked list is known as the head of the list. It is not a different node, but refers to the first node.
The node present in the end is called NULL.
When a node holds a data part and two addresses, it is known as a doubly-linked list. Two addresses means a
pointer to the previous node and the next node.
In a circular linked list, the last node of the series contains the address of the first node to make a circular chain.
Basic Operations In Linked List
When it comes to linked lists, there are five operations supported by the series or list.
The work of the data segment is to hold an actual piece of information, and the work of the link or address field
stores the address of the next node. Insertion, deletion, and traversing are some operations that we can perform
on a singly linked list.
Here, the previous pointer contains the address of the previous node, and similarly, the other pointer contains
the address of the next node.
1 In case of singly linked lists, the complexity of insertion In case of doubly linked lists, the complexity of
and deletion is O(n) insertion and deletion is O(1)
2 The Singly linked list has two segments: data and link. The doubly linked list has three segments. First is
data and second, third are the pointers.
3 It permits traversal components only in one way. It permits two way traversal.
4 We mostly prefer a singly linked list for the execution of We can use a doubly linked list to execute binary
stacks. trees, heaps and stacks.
5 When we want to save memory and do not need to In case of better implementation, while searching,
perform searching, we prefer a singly linked list. we prefer a doubly linked list.
6 A singly linked list consumes less memory as compared The doubly linked list consumes more memory as
to the doubly linked list. compared to the singly linked list.
10.What is Array?
An array is a grouping of data elements or data items stored in contiguous memory. An array is one of the most
simple data structures where we can easily access the data element by only using its index number.
An array is a grouping of data elements of equivalent A linked list is a group of entities called a node. The
1. data type. node includes two segments: data and address.
It stores the data elements in a contiguous memory It stores elements randomly, or we can say anywhere
2. zone. in the memory zone.
In the case of an array, memory size is fixed, and it is In the linked list, the placement of elements is
3. not possible to change it during the run time. allocated during the run time.
4. The elements are not dependent on each other. The data elements are dependent on each other.
5. The memory is assigned at compile time. The memory is assigned at run time.
It is easier and faster to access the element in an In a linked list, the process of accessing elements
6. array. takes more time.
In the case of an array, memory utilization is In the case of the linked list, memory utilization is
7. ineffective. effective.
When it comes to executing any operation like When it comes to executing any operation like
8 insertion, deletion, array takes more time. insertion, deletion, the linked list takes less time.
11.STACKS
A Stack is linear data structure. A stack is a list of elements in which an element may be inserted or deleted only at
one end, called the top of the stack.
Stack principle is LIFO (last in, first out). Which element inserted last on to the stack that element deleted first
from the stack.
A Stack is a linear data structure. In case of an array, random access is possible, i.e., any element of an array can
be accessed at any time, whereas in a stack, the sequential access is only possible. It is a container that
follows the insertion and deletion rule. It follows the principle LIFO (Last In First Out) in which the
insertion and deletion take place from one side known as a top. In stack, we can insert the elements of a
similar data type, i.e., the different data type elements cannot be inserted in the same stack. The two
operations are performed in LIFO, i.e., push and pop operation.
Real life examples of stacks are:
Operations on stack:
The two basic operations associated with stacks are:
1. Push:
Push operation is used to add new elements into the stack.
The new element is added at the topmost position of the stack.
At the time of addition first check the stack is full or not. If the stack is full, it generates an error message "stack
overflow".
2. Pop:
The pop operation is used to delete the topmost element from the stack.
At the time of deletion first check the stack is empty or not. If the stack is empty, it generates an error message
"stack underflow".
While performing push and pop operations the following test must be conducted on the stack.
1) Stack is empty or not.
2) Stack is full or not.
Advantages of Stack
A Stack helps to manage the data in the ‘Last in First out’ method.
When the variable is not used outside the function in any program, the Stack can be used.
It allows you to control and handle memory allocation and deallocation.
It helps to automatically clean up the objects.
Disadvantages of Stack
It is difficult in Stack to create many objects as it increases the risk of the Stack overflow.
It has very limited memory.
In Stack, random access is not possible.
Note:
All insertions and deletions take place at the same end, so the last element added to the stack will be the first
element removed from the stack.
When a stack is created, the stack base remains fixed while the stack top changes as elements are added and
removed.
The most accessible element is the top and the least accessible element is the bottom of the stack.
There are two types of Stacks: They are the Register Stack and the Memory Stack.
Implementation of stack:
The stack should be represented in two ways:
1) Stack using array.
2) Stack using linked list.
Initially top=-1, we can insert an element into the stack, increment the top value i.e., top=top+1.
We can insert an element into the stack first check the condition is stack is full or not. i.e., top>=size-1. Otherwise
add the element in to the stack.
We can insert an element from the stack, decrement the top value i.e., top=top-1.
We can delete an element from the stack first check the condition is stack is empty or not.
i.e. top==-1. Otherwise remove the element from the stack.
Void pop() Algorithm: procedure pop():
{ Step 1: START
If(top==-1) Step 2: if top==-1 then
{ Write “Stack is Underflow”
Printf(“Stack is Underflow”); Step 3: otherwise
} 3.1: print “deleted element”
else 3.2: top=top-1;
{ Step 4: END
printf(“Delete data %d”,stack[top]);
top=top-1;
}
}
display():
This operation performed display the elements in the stack.
We display the element in the stack check the condition is stack is empty or not i.e., top==-1. Otherwise display the
list of elements in the stack.
Push Operation
The push operation is used to insert an element into the stack. The new element is added at the topmost position of
the stack. Consider the linked stack shown in below figure.
To insert an element with value 9, we first check if TOP=NULL. If this is the case, then we allocate memory for a new
node, store the value in its DATA part and NULL in its NEXT part. The new node will then be called TOP.
However, if TOP!=NULL, then we insert the new node at the beginning of the linked stack and name this new node as
TOP.
Pop Operation
The pop operation is used to delete the topmost element from a stack.
However, before deleting the value, we must first check if TOP=NULL, because if this is the case, then it means that
the stack is empty, and no more deletions can be done.
If an attempt is made to delete a value from a stack that is already empty, an UNDERFLOW message is printed.
Consider the stack shown in below figure.
In case TOP!=NULL, then we will delete the node pointed by TOP, and make TOP point to the second element of the
linked stack. Thus, the updated stack becomes as shown in below figure.
Applications of stack:
a) Stack is used by compilers to check for balancing of parentheses, brackets, and braces.
b) Stack is used to evaluate a postfix expression.
c) Stack is used to convert an infix expression into postfix/prefix form.
d) In recursion, all intermediate arguments and return values are stored on the processor’s stack.
e) During a function call the return address and arguments are pushed onto a stack and on return they are popped off.
15.QUEUE
A queue is linear data structure and collection of elements.
The principle of queue is a “FIFO” or “First-in-first-out”.
A queue is another special kind of list, where items are inserted at one end called the rear and deleted at the other
end called the front.
Queue is an abstract data structure. A queue is a useful data structure in programming.
A real-world example of queue can be a single-lane one-way road, where the vehicle enters first, exits first.
The operations for a queue are analogues to those for a stack; the difference is that the insertions go at the end of
the list, rather than the beginning.
Operations on QUEUE:
A queue is an object or more specifically an abstract data structure (ADT) that allows the following operations:
1. Enqueue or insertion: which inserts an element at the end of the queue.
2. Dequeue or deletion: which deletes an element at the start of the queue.
Implementation of Queue:
The queue can be represented in two ways:
1. Queue using Array
2. Queue using Linked List
Again, insert another element 33 to the queue. The status of the queue is:
Now, delete an element. The element deleted is the element at the front of the queue. So the status of the
queue is:
Again, delete an element. The element to be deleted is always pointed to by the FRONT pointer. So, 22 is
deleted. The queue status is as follows:
Now, insert new elements 44 and 55 into the queue. The queue status is:
Next insert another element, say 66 to the queue. We cannot insert 66 to the queue as the rear crossed the
maximum size of the queue (i.e., 5). There will be queue full signal. The queue status is as follows:
Now it is not possible to insert an element 66 even though there are two vacant positions in the linear queue.
To overcome this problem the elements of the queue are to be shifted towards the beginning of the queue so
that it creates vacant position at the rear end. Then the FRONT and REAR are to be adjusted properly.
The element 66 can be inserted at the rear end. After this operation, the queue status is as follows:
Note:
This difficulty can overcome if we treat queue position with index 0 as a position that comes after position with
index 4 i.e., we treat the queue as a circular queue.
Queue operations using array:
1) enqueue() or insertion():which inserts an element at the end of the queue.
void insertion() Algorithm: Procedure for insertion():
{ Step-1:START
if(rear==max) Step-2: if rear==max then
printf("\n Queue is Full"); Write ‘Queue is full’
else Step-3: otherwise
{ 3.1: read element ‘queue[rear]’
printf("\n Enter no %d:",j++); Step-4:STOP
scanf("%d",&queue[rear++]);
}
}
Applications of Queue:
1. It is used to schedule the jobs to be processed by the CPU.
2. When multiple users send print jobs to a printer, each printing job is kept in the printing queue. Then the printer prints
those jobs according to first in first out (FIFO) basis.
3. Breadth first search uses a queue data structure to find an element from a graph.
4. In real life, Call Center phone systems will use Queues, to hold people calling them in an order, until a service
representative is free.
5. Handling of interrupts in real - time systems. The interrupts are handled in the same order as they arrive, First come
first served.
18.CIRCULAR QUEUE
Once the queue gets filled up, no more elements can be added to it even if any element is removed from it
consequently. This is because during deletion, rear pointer is not adjusted.
When the queue contains very few items and the rear pointer points to last element. i.e. rear=maxSize-1, we cannot
insert any more items into queue because the overflow condition satisfies.
That means a lot of space is wasted. Frequent reshuffling of elements is time consuming. One solution to this is
arranging all elements in a circular fashion. Such structures are often referred to as Circular Queues.
A circular queue is a queue in which all locations are treated as circular such that the first location CQ[0] follows the
last location CQ[max-1].
A more efficient queue representation is obtained by regarding the array Q[MAX] as circular. Any number of items
could be placed on the queue.
This implementation of a queue is called a circular queue because it uses its storage array as if it were a circle instead
of a linear list.
Next insert another element, say 66 to the queue. We cannot insert 66 to the queue as the rear crossed the
maximum size of the queue (i.e., 5). There will be queue full signal. The queue status is as follows:
This difficulty can be overcome if we treat queue position with index zero as a position that comes after position with
index four then we treat the queue as a circular queue.
In circular queue if we reach the end for inserting elements to it, it is possible to insert new elements if the slots at
the beginning of the circular queue are empty.
Insert new elements 22, 33, 44 and 55 into the circular queue. The circular queue status is:
Now, delete an element. The element deleted is the element at the front of the circular queue. So, 11 is deleted. The
circular queue status is as follows:
Again, delete an element. The element to be deleted is always pointed to by the FRONT pointer. So, 22 is deleted.
The circular queue status is as follows:
Again, insert another element 66 to the circular queue. The status of the circular queue is:
Now, insert new elements 77 and 88 into the circular queue. The circular queue status is:
Now, if we insert an element to the circular queue, as COUNT = MAX we cannot add the element to circular queue.
So, the circular queue is full.
Operations on Circular queue:
1. enqueue() or insertion():This function is used to insert an element into the circular queue. In a circular queue,
the new element is always inserted at Rear position.
void insertCQ() Algorithm: procedure of insertCQ():
{ Step-1:START
int data; Step-2: if count==MAX then
if(count ==MAX) { Write “Circular queue is full”
printf("\n Circular Queue is Full"); Step-3:otherwise
} 3.1: read the data element
else { 3.2: CQ[rear]=data
printf("\n Enter data: "); 3.3: rear=(rear+1)%MAX
scanf("%d", &data); 3.4: count=count+1
CQ[rear] = data; Step-4:STOP
rear = (rear + 1) % MAX;
count ++;
printf("\n Data Inserted in the
Circular Queue ");
}
}
2. dequeue() or deletion():This function is used to delete an element from the circular queue. In a circular
queue, the element is always deleted from front position.
void deleteCQ() Algorithm: procedure of deleteCQ():
{ Step-1:START
if(count ==0) { Step-2: if count==0 then
printf("\n\nCircular Queue is Empty.."); Write “Circular queue is empty”
} Step-3:otherwise
else { 3.1: print the deleted element
printf("\n Deleted element from Circular Queue 3.2: front=(front+1)%MAX
is %d ", CQ[front]); 3.3: count=count-1
front = (front + 1) % MAX; Step-4:STOP
count --;
}
}
3. c.dispaly():This function is used to display the list of elements in the circular queue.
void displayCQ() Algorithm: procedure of displayCQ():
{ Step-1:START
int i, j; Step-2: if count==0 then
if(count ==0) { Write “Circular queue is empty”
printf("\nCircular Queue is Empty "); Step-3:otherwise
} 3.1: print the list of elements
else { 3.2: for i=front to j!=0
printf("\n Elements in Circular Queue 3.3: print CQ[i]
are: "); 3.4: i=(i+1)%MAX
j = count; Step-4:STOP
for(i = front; j != 0; j--)
{
printf("%d\t", CQ[i]);
i = (i + 1) % MAX;
}
}
}
19.Deque:
In the preceding section we saw that a queue in which we insert items at one end and from which we remove items
at the other end.
In this section we examine an extension of the queue, which provides a means to insert and remove items at both
ends of the queue. This data structure is a deque.
The word deque is an acronym derived from double-ended queue. Below figure shows the representation of a
deque.
20.Priority Queue:
A priority queue is a collection of elements such that each element has been assigned a priority.
A priority queue is a collection of zero or more elements. Each element has a priority or value.
Unlike the queues, which are FIFO structures, the order of deleting from a priority queue is determined by the
element priority.
Elements are removed/deleted either in increasing or decreasing order of priority rather than in the order in
which they arrived in the queue.
There are two types of priority queues:
Min priority queue: Collection of elements in which the items can be inserted arbitrarily, but only smallest element
can be removed.
Max priority queue: Collection of elements in which insertion of items can be in any order but only largest element
can be removed.
In priority queue, the elements are arranged in any order and out of which only the smallest or largest element
allowed to delete each time.
The implementation of priority queue can be done using arrays or linked list. The data structure heap is used to
implement the priority queue effectively.
We can insert an element in priority queue at the rare position.
We can delete an element from the priority queue based on the element’s priority and such that the order in which
elements are deleted and processed comes from the following rules:
1. An element of higher priority is processed before any element of lower priority.
2. Two elements with same priority are processed according to the order in which they were added to the queue. It
follows FIFO or FCFS (First Comes First serve) rules.
We always remove an element with the highest priority, which is given by the minimal integer priority assigned.
A prototype of a priority queue is time sharing system: programs of high priority are processed first, and programs
with the same priority form a standard queue.
An efficient implementation for the Priority Queue is to use heap, which in turn can be used for sorting purpose
called heap sort.
APPLICATIONS:
1. The typical example of priority queue is scheduling the jobs in operating system. Typically, OS allocates priority to jobs.
The jobs are placed in the queue and position of the job in priority queue determines their priority. In OS there are 3
jobs- real time jobs, foreground jobs and background jobs. The OS always schedules the real time jobs first. If there is
no real time jobs pending then it schedules foreground jobs. Lastly if no real time and foreground jobs are pending
then OS schedules the background jobs.
2. In network communication, the manage limited bandwidth for transmission the priority queue is used.
3. In simulation modelling to manage the discrete events the priority queue is used.
2. Through sorted List (Using Linked List): In this case insertion is costly because the element inserts at the proper place
in the list based on the priority. Here deletion is easy since the element with highest priority will always be in the
beginning of the list.
21.Difference between stacks and Queues?
Parameter Stack Data Structure Queue Data Structure
Basics It is a linear data structure. The It is also a linear data structure. The objects are
objects are removed or inserted at the removed and inserted from two different ends.
same end.
Working Principle It follows the Last In, First Out It follows the First In, First Out (FIFO) principle. It
(LIFO) principle. It means that the last means that the first added element gets removed first
inserted element gets deleted at first. from the list.
Pointers It has only one pointer- the top. This It uses two pointers (in a simple queue) for reading and
pointer indicates the address of the writing data from both the ends- the front and
topmost element or the last inserted the rear. The rear one indicates the address of the last
one of the stack. inserted element, whereas the front pointer indicates
the address of the first inserted element in a queue.
Operations Stack uses push and pop as two of its Queue uses enqueue and dequeue as two of its
operations. The pop operation operations. The dequeue operation deletes the elements
functions to remove the element from from the queue, and the enqueue operation inserts the
the list, while the push operation elements in a queue.
functions to insert the element in a
list.
Structure Insertion and deletion of elements take It uses two ends- front and rear. Insertion uses the rear
place from one end only. It is called end, and deletion uses the front end.
the top.
Full Condition When top== max-1, it means that the When rear==max-1, it means that the queue is full.
Examination stack is full.
Empty Condition When top==-1, it indicates that the When front = rear+1 or front== -1, it indicates that the
Examination stack is empty. queue is empty.
Variants A Stack data structure does not have A Queue data structure has three types- circular queue,
any types. priority queue, and double-ended queue.
Visualization You can visualize the Stack as a You can visualize a Queue as a horizontal collection.
vertical collection.
In general, operations that require adding and removing pieces from both ends of the data structure are faster
with queues. When only adding and removing elements at one end of the data structure is required, stacks are
faster.
Nevertheless, the performance difference between stacks and queues is typically insignificant, therefore the
decision should be made depending on the particular requirements of the programme.
The way elements are accessible in each data structure in turn determines how quickly stacks and queues
operate. The most recently inserted element is the first one to be removed when accessing items in a stack in a
Last-In-First-Out (LIFO) way. This makes adding and removing pieces from the top of the stack simple, but it
can take some time to access elements in the middle or at the bottom of the stack.
The first element added to an existing queue is the first one deleted when elements in a queue are accessed
using the First-In-First-Out (FIFO) principle. This makes it simple to add and remove components from the
queue's ends, but it may take some time to access elements in the middle of the queue.
In conclusion, the specific requirements of the programme should be taken into account when deciding between
stacks and queues. A queue would be a preferable option if the programme often adds and removes elements
from both ends of the data structure. A stack would be a preferable option if the programme often adds and
removes components from just one end of the data structure.
1. The queue is used as a waiting list when the resource is to be shared with multiple systems. For example, CPU
scheduling or disk scheduling.
2. It is used in the operating system for FCFS scheduling, semaphores, buffer for devices and spooling the printers.
3. Queues are used in routers and switches.
4. In networking, the queue is used when data is transferred asynchronously.
5. It is utilized in maintaining the playlist in media players.
6. It is also a part of the round-robin scheduling algorithm.
Meaning The linear queue is a type of The circular queue is also a linear data
linear data structure that structure in which the last element of the
contains the elements in a Queue is connected to the first element,
sequential manner. thus creating a circle.
Insertion and In linear queue, insertion is In circular queue, the insertion and
Deletion done from the rear end, and deletion can take place from any end.
deletion is done from the front
end.
Memory space The memory space occupied by It requires less memory as compared to
the linear queue is more than linear queue.
the circular queue.
Order of It follows the FIFO principle in It has no specific order for execution.
execution order to perform the tasks.
Types of Traversals
Types of Traversals the Binary Search Tree can be traversed in the following ways:
In preorder traversal, we start from the current node before going on to the left and right nodes.
In inorder traversal, we can traverse from the left node then hitting the current node and at the last right node.
In postorder traversal, we can start by traversing from the left child node before the right child node and then the
current node.
Advantages:
The binary search tree is fast in insertion and deletion etc when balanced.
It is very effective, and its code is easier as compared to the link lists.
Disadvantages:
The shape of the tree depends upon the order of insertion, and it can degenerate.
In binary search trees, searching operations take a longer time.
Comparison Right Binary Tree Vs Wrong Binary Search Tree
23.What is Graph?
A graph is a non-linear data structure that permits you to define connections between different types of data
(nodes). Or we can say that a graph is a data structure that is built with the help of nodes or vertices and edges(arcs).
Types of Graphs
Finite Graph: If a graph has a finite number of vertices and a finite number of edges, it is known as a finite graph.
Infinite Graph: If a graph has an infinite number of vertices and an infinite number of edges, it is known as an infinite
graph.
Trivial Graph: If a finite graph has only a single vertex and no edge, it is known as a trivial graph.
Simple Graph: A graph that contains only one edge between the pair of vertices is known as a simple graph.
Multi Graph: If there are multiple edges or points between a set of vertices in a graph, it is known as a
multigraph.
Null Graph: A graph that does not include any edges in it is known as a null graph.
Complete Graph: A complete graph is also known as a full graph because each vertex’s degree should be n-1.
Pseudo Graph: If a graph has a self-loop with other edges it is known as a pseudo graph.
Regular Graph: If each vertex has the same degree, it is known as a regular graph.
Weighted Graph: A graph in which each edge has numbers or values is known as a weighted graph. It is a
special type of graph.
Directed Graph: A directed graph, also referred to as a digraph, is a collection of vertices combined by edges,
each with a direction.
Undirected Graph: An undirected graph comprises a set of nodes and links connecting them. The order of the two
connected vertices is irrelevant and has no direction. You can form an undirected graph with a finite number of
vertices and edges.
Connected Graph: If there is a path between one vertex of a graph data structure and any other vertex, the graph
is connected.
Graph Representation
There are two techniques to represent a graph:
1. Adjacency Matrix
In the adjacency matrix, each row and column define a vertex. It is a 2D array of V x V vertices.
2. Adjacency List
The index of the array defines a vertex, and every component in its linked list describes the other vertices that
form an edge with the vertex.