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

Module No 2 Linear Data Structures

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Module No 2 Linear Data Structures

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 90

Data Structures and

Algorithms
Course Code: CSE2001
MODULE – 2
(Linear Data Structures)
Data Structures
Types of Linear Data Structures

A Linear data structure have data elements arranged in sequential manner


and each member element is connected to its previous and next element.
except for the first and last elements. Here are some common types of linear
data structures:
Arrays in Data Structures
Arrays in Data Structures
 Array is a container which can hold a fix number of items and these items
should be of the same type.

 Arrays are a fundamental data structure in computer science. They are used in a
wide variety of applications, including:
 Storing data for processing
 Implementing data structures such as stacks and queues
 Representing data in tables and matrices
 Creating dynamic data structures such as linked lists and trees

 Following are the important terms to understand the concept of Array.


 Element − Each item stored in an array is called an element.
 Index − Each location of an element in an array has a numerical index, which is used
to identify the element.
Arrays in Data Structures

 Index starts with 0.


 Array length is 10 which means it can store 10 elements.
 Each element can be accessed via its index. For example, we can
fetch an element at index 6 as array[6].
Types of Arrays

 There are two main types of arrays:


 One-dimensional arrays: These arrays store a single row of elements.
 Multidimensional arrays: These arrays store multiple rows of
elements.

One-dimensional array
Two-dimensional array
Declaration of Array

Syntax: data_type array_name[array_size]

Example: An array integer can be declared as follows


int example[5]

0 1 2 3 4
Declaration of Array
Method-01 Int a[5] = [1,2,3,4,5]; [1,2,3,4,5]
Method-02 Int a[] = {1,2,3,4,5} [1,2,3,4,5]
Int a[5];
a[0]=1
Method-03 a[1]=2 [1,2,3,4,5]
a[2]=3
a[3]=4
a[4]=5

Method-04 Int a[5];


for(i=0;i<5;i++){ [1,2,3,4,5]
scanf(“%d”,a[i]);
}
Accessing Array Elements
operations on a linear array

We can perform various operations on a linear array:


 Traversing- processing each element of the array list.
 Inserting- adding new elements in the array list.
 Deleting- removing an element from the array list.
 Sorting- arranging the elements of the list in some sorting order.
 Searching- Searching an element in array
 Merging- combining the elements of two array lists in a single array
list.
Traversing Linear Array

Traversing Linear Array:


 We can process each element of an array with the help of an index set.
 Consider a Linear Array(LA) list given with lower bound(LB) and upper
bound(UB) that contains 'n' number of elements. We can traverse
the list with the given algorithm.
ALGORITHM
(initialized counter) K = LB
Repeat
while k <= UB
Process LA[k]
K = k + 1(End of loop)
Exit
Traversing Linear Array
#include <iostream>
Output:
int main() {
// Declare and initialize an array
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array

// Traverse the array


for (int i = 0; i < size; i++) {
std::cout << "Element at index " << i << ": " << arr[i] << std::endl;
}

return 0;
}
Insertion element into Array

 Array insertion, of an element at the end of the list, is quite simple.


 If we need to insert an element in the middle of an array, lots of internal
shifting is required to insert the new element. I.e. half of the elements must
be moved downward, to the new location, to enter the new element
Algorithm
(Here, LA is a linear array with n number of elements, where K is a positive integer, i.e. K<=n. This algorithm inserts an element
item into the Kth position.)

(Initialized counter) J = n
Repeat step 3 & 4
while j >= k[Move downward] set LA[J + 1] = LA[J]
[Decrement counter] set j = j - 1;
End of step 2[Insert element] set LA[k] = ITEM[Reset n] set n = n + 1
Exit
Insertion element into Array
#include <iostream>

int main() {

int arr[6] = {10, 20, 30, 40, 50}; // Declare and initialize an array

int size = 5; // Current size of the array

int element = 25; // Element to be inserted

int position = 2; // Position to insert the element (0-based index)

for (int i = size; i > position; i--) { // Shift elements to the right to make space for the new element

arr[i] = arr[i - 1];

arr[position] = element; // Insert the new element

size++; // Update the size of the array

std::cout << "Array after insertion: "; // Display the array after insertion

for (int i = 0; i < size; i++) {

std::cout << arr[i] << " ";

std::cout << std::endl; Output


return 0;

}
Deletion element into Array
 if we need to delete an element from the middle of the array, then on
average, half of the elements must be moved upward, in order to fill the
blank space, after deleting the element from the specified location.
Algorithm
(Here, LA is a linear array with 'n' number of elements and K is a positive integer number, such that k<=N. This
algorithm removes the element from the Kth position)

Set Item = LA[k]


Repeat
for J = k to N - 1[move J + 1 st element upward] LA[J] = LA[J
+ 1]
[End of step 2]
[Reset the number of element] N = N - 1
Exit
Deletion element into Array
#include <iostream>

#include <string>

int main() {

int n = 5;

std::string name[] = {"mike", "rick", "max", "christ", "larry"};

int k = 2; // Position to delete the element

std::cout << "Elements before deleting the element:\n"; // Display elements before deletion

for (int i = 0; i < n; i++) {

std::cout << "Position(" << i << ") " << name[i] << std::endl;

for (int j = k; j < n - 1; j++) { // Deleting the element

name[j] = name[j + 1]; }


Output
n = n - 1;

std::cout << "\nElements after deleting the element:\n"; // Display elements after deletion

for (int i = 0; i < n; i++) {

std::cout << "Position(" << i << ") " << name[i] << std::endl;

return 0;

}
Sorting of Array
#include <iostream>

int main() {

int n = 5;

int numbers[] = {34, 7, 23, 32, 5}; Output:


std::cout << "Elements before sorting:\n"; // Display elements before sorting

for (int i = 0; i < n; i++) {

std::cout << "Position(" << i << ") " << numbers[i] << std::endl; }

for (int i = 0; i < n - 1; i++) { // Simple selection sort to sort


the array

int minIndex = i;

for (int j = i + 1; j < n; j++) {

if (numbers[j] < numbers[minIndex]) {

minIndex = j; }}

if (minIndex != i) {

int temp = numbers[i];

numbers[i] = numbers[minIndex];

numbers[minIndex] = temp; }}

std::cout << "\nElements after sorting:\n"; // Display elements after sorting

for (int i = 0; i < n; i++) {

std::cout << "Position(" << i << ") " << numbers[i] << std::endl; }

return 0; }
Searching Output:
#include <iostream>

int main() {

int n = 5;

int numbers[] = {34, 7, 23, 32, 5};

int target = 23; // Element to search for

std::cout << "Array elements:\n"; // Display elements

for (int i = 0; i < n; i++) {

std::cout << "Position(" << i << ") " << numbers[i] << std::endl; }

int foundIndex = -1; // Perform linear search

for (int i = 0; i < n; i++) {

if (numbers[i] == target) {

foundIndex = i;

break; }}

if (foundIndex != -1) { // Display search result

std::cout << "\nElement " << target << " found at position " << foundIndex << ".\n";

} else {

std::cout << "\nElement " << target << " not found in the array.\n";}

return 0;

}
Merging
#include <iostream>

int main() { Output:


int n1 = 5; // Define two arrays

int n2 = 3;

int array1[] = {1, 3, 5, 7, 9};

int array2[] = {2, 4, 6};

int mergedSize = n1 + n2; // Define the merged array

int mergedArray[mergedSize];

for (int i = 0; i < n1; i++) { // Copy elements from the first array to the
merged array

mergedArray[i] = array1[i]; }

for (int i = 0; i < n2; i++) { // Copy elements from the second array to the
merged array

mergedArray[n1 + i] = array2[i]; }

std::cout << "Merged array:\n"; // Display merged array

for (int i = 0; i < mergedSize; i++) {

std::cout << mergedArray[i] << " "; }

std::cout << std::endl;


Advantages of Arrays

 Arrays stores multiple elements of same type with the same


name.
 Elements in array can accessed randomly using an index number.
 Array memory is predefined, so there is no extra memory loss.
 Array avoid memory overflow.
 2D arrays can represent the tabular data in an efficient way.
Stacks in Data Structures
Stacks in Data Structures

 A Stack is a linear data structure that follows a particular order in


which the operations are performed.
 The order may be LIFO(Last In First Out) or FILO(First In Last
Out).
 LIFO implies that the element that is inserted last, comes out first
and FILO implies that the element that is inserted first, comes out
last.
 It behaves like a stack of plates, where the last plate added is the
first one to be removed.
 Pushing an element onto the stack is like adding a new plate on
top.
 Popping an element removes the top plate from the stack.
Stacks in Data Structures
 Real-Life Example: Stack of Books
 Adding Books to the Stack:
 Imagine you have a stack of books on your desk.
 Each time you get a new book, you place it on top of the stack.
 For example, if you have three books in the order Book1, Book2, and Book3,
and you get a new Book4, you place Book4 on top of Book3.
 Removing Books from the Stack :
 When you need to use a book, you always take the book from the top of the
stack.
 For instance, if you need a book, you take Book4 first since it's on the top.
 After removing Book4, Book3 becomes the top book.
Representation of Stack
Array Representation of Stack

 In this method, an array is used to represent the stack.


 Variables in this Method:
 STACK – Name of the array
 TOP – Storing the index where the last is held in an array representing
the stack.
 MAX – Define how many maximum elements can be stored In array or the
size of the stack.
Key Operations on Stack Data
Structures
 Push(): Adds an element to the top of the stack.
 Pop(): Removes the top element from the stack.
 Peek(): Returns the top element without removing it.
 IsEmpty(): Checks if the stack is empty.
 IsFull(): Checks if the stack is full (in case of fixed-size arrays).
Key Operations on Stack Data
Structures
Push operation in stack
The steps involved in the PUSH operation is given below:
 Before inserting an element in a stack, we check whether the stack is
full.
 If we try to insert the element in a stack, and the stack is full, then
the overflow condition occurs.
 When we initialize a stack, we set the value of top as -1 to check that the
stack is empty.
 When the new element is pushed in a stack, first, the value of the top
gets incremented, i.e., top=top+1, and the element will be placed at
the new position of the top.
 The elements will be inserted until we reach the max size of the stack.
Pop operation in stack

The steps involved in the POP operation is given below:


 Before deleting the element from the stack, we check whether the
stack is empty.
 If we try to delete the element from the empty stack, then
the underflow condition occurs.
 If the stack is not empty, we first access the element which is
pointed by the top
 Once the pop operation is performed, the top is decremented by 1,
i.e., top=top-1.
Peek operation in stack
The steps involved in the Peek operation is given below:
 Before accessing the top element of the stack, we check whether the
stack is empty.
 If the stack is empty, then the underflow condition occurs, and the
operation cannot be performed. Typically, an error message is displayed, or
an exception is thrown to indicate that the stack is empty.
 If the stack is not empty, we access the element that is pointed to by the
top pointer.
 The top pointer gives us the position of the most recently added element
in the stack.
 The element at the top of the stack is returned as the result of the Peek()
operation.
 Unlike the POP operation, the Peek() operation does not modify the stack.
The top pointer remains unchanged.
Applications of Stack

 Expression Conversion
 Check Parenthesis
 Memory Management and Function call
 Back Tracking
 String Reversal
 Conversion Evolution
 Tower of Hanoi
Expression Conversion

An infix and postfix are the expressions.

An expression consists of constants, variables, and symbols.

Symbols can be operators or parenthesis.

All these components must be arranged according to a set of rules so


that all these expressions can be evaluated using the set of rules.
infix Expression

 Infix Expression
5 + 6, A – B, (P * 5)
Syntax: <operand> <operator> <operand>
 If the expression is: 4+6*2
 If the plus operator is evaluated first, then the expression would look like: 10 * 2 = 20
 If the multiplication operator is evaluated first, then the expression would look like:
4 + 12 = 16
operator precedence rules

Higher

Lower
 For example: 2^2^3 = 2 ^ 8 = 256

 After exponent, multiplication, and division operators are evaluated. If both


the operators are present in the expression, then the operation will be
applied from left to right.

 The next preference is given to addition and subtraction. If both the


operators are available in the expression, then we go from left to right.

 The operators that have the same precedence termed as operator


associativity. If we go from left to right, then it is known as left-
associative. If we go from right to left, then it is known as right-associative.
 The use of parenthesis is very important in infix notation to control
the order in which the operation to be performed.
 Parenthesis improves the readability of the expression.
 An infix expression is the most common way of writing expression,
but it is not easy to parse and evaluate the infix expression without
ambiguity.
 So, mathematicians and logicians studied this problem and
discovered two other ways of writing expressions which are prefix and
postfix.
 Both expressions do not require any parenthesis and can be parsed
without ambiguity.
 It does not require operator precedence and associativity rules.
Postfix Expression

 The postfix expression is an expression in which the operator is


written after the operands. For example, the postfix expression of
infix notation ( 2+3) can be written as 23+.
Syntax (operand1 operand2 operator).
Example : AB+CD-* (Infix : (A+B * (C-D) )
Some key points regarding the postfix expression are:
 In postfix expression, operations are performed in the order in which
they have written from left to right.
 It does not any require any parenthesis.
 We do not need to apply operator precedence rules and associativity
rules.
Why postfix representation of the expression?
 Infix expressions are readable and solvable by humans because of
easily distinguishable order of operators, but compiler doesn't have
integrated order of operators.

 Hence to solve the Infix Expression compiler will scan the expression
multiple times to solve the sub-expressions in expressions orderly
which is very in-efficient.

 To avoid this traversing, Infix expressions are converted to Postfix


expression before evaluation.
Prefix expression

 An expression is called the prefix expression if the operator appears


in the expression before the operands.

Simply of the form (operator operand1 operand2).


Example : *+AB-CD (Infix : (A+B) * (C-D) )
Problems on
 Infix to Postfix conversion with an algorithm
 Infix to Prefix conversion with an algorithm
 Prefix to Postfix conversion with an algorithm

43
Queues in Data Structures
Queues

 A queue is a useful data structure in programming.


 It is similar to the ticket queue outside a cinema hall, where the first
person entering the queue is the first person who gets the ticket.
 Queue follows the First In First Out (FIFO) rule - the item that goes
in first is the item that comes out first.
since 1 was kept in the queue
before 2, it is the first to be
removed from the queue as well.
It follows the FIFO rule.

In programming terms, putting


items in the queue is
called enqueue, and removing
items from the queue is
called dequeue.
Array Representation of Queue

Syntax:
Data_type queue_name[size]
Int FRONT=-1
Int REAR=-1

Example:
Queue = MyQueue[10]
Int FRONT=-1
Int REAR=-1
Working of Queue

The Queue operations work as follows:

 two pointers FRONT and REAR

 FRONT track the first element of the queue

 REAR track the last element of the queue Empty Queue

 initially, set value of FRONT and REAR to -1


Key Operations on Queue Data
Structures
A queue is an object (an abstract data structure - ADT) that allows the
following operations:
 Enqueue(): Add an element to the end of the queue
 Dequeue(): Remove an element from the front of the queue
 IsEmpty(): Check if the queue is empty
 IsFull(): Check if the queue is full
 Peek(): Get the value of the front of the queue without removing
it
Enqueue() operation in Queue

 The steps involved in the Enqueue() operation is given below:


 Check if the Queue is FULL.
 If the queue is full, produce OVERFLOW ERROR and Exit.
 If the queue is not full, increment RARE pointer to point the next
element space.
 Add DATA element to the queue location, where the REAR is
pointing.
 Element is added successfully.
 The elements will be inserted until we reach the RARE==size-1
Dequeue() operation in Queue

 The steps involved in the Enqueue() operation is given below:


 Check If the queue is EMPTY
 If the queue is empty, produce UNDERFLOW ERROR and exit.
 If the queue is not empty, access the data where FRONT is pointing.
 INCREMENT FRONT pointer to point to the next available data.
 Element is Removed Successfully.
Types of Deque
 Input Restricted Deque
In this deque, input is restricted at a single end but allows deletion at both the ends.
 Output Restricted Deque
In this deque, output is restricted at a single end but allows insertion at both the
ends.
Operations on a Deque
 The circular array implementation of deque is considered. In a circular array, if the
array is full, we start from the beginning.
 But in a linear array implementation, if the array is full, no more elements can be
inserted. In each of the operations below, if the array is full, "overflow message" is
thrown.
Insert at the front

In this operation, the element is inserted from the front end of the queue. Before
implementing the operation, we first have to check whether the queue is full or not. If
the queue is not full, then the element can be inserted from the front end by using
the below conditions -
 If the queue is empty, both rear and front are initialized with 0. Now, both will
point to the first element.
 Otherwise, check the position of the front if the front is less than 1 (front < 1),
then reinitialize it by front = n - 1, i.e., the last index of the array.

11/12/2024 52
Insertion at Rear End

In this operation, the element is inserted from the rear end of the queue. Before
implementing the operation, we first have to check again whether the queue is full or
not. If the queue is not full, then the element can be inserted from the rear end by
using the below conditions –
 If the queue is empty, both rear and front are initialized with 0. Now, both will
point to the first element.
 Otherwise, increment the rear by 1. If the rear is at last index (or size - 1), then
instead of increasing it by 1, we have to make it equal to 0.

11/12/2024 53
Deletion at Front end

In this operation, the element is deleted from the front end of the queue. Before
implementing the operation, we first have to check whether the queue is empty or
not.
If the queue is empty, i.e., front = -1, it is the underflow condition, and we cannot
perform the deletion. If the queue is not full, then the element can be inserted from
the front end by using the below conditions -
 If the deque has only one element, set rear = -1 and front = -1.
 Else if front is at end (that means front = size - 1), set front = 0.
 Else increment the front by 1, (i.e., front = front + 1).

11/12/2024 54
Deletion at rear end

 In this operation, the element is deleted from the rear end of the queue. Before
implementing the operation, we first have to check whether the queue is empty or
not.
 If the queue is empty, i.e., front = -1, it is the underflow condition, and we cannot
perform the deletion.
 If the deque has only one element, set rear = -1 and front = -1.
 If rear = 0 (rear is at front), then set rear = n - 1.
 Else, decrement the rear by 1 (or, rear = rear -1).
IsEmpty() operation in Queue

 Begin procedure isEmpty().


 If FRONT is equal to NULL(-1)
 Return “QUEUE IS EMPTY”
 END of procedure Peek.

Empty Queue
IsFull() operation in Queue

 Begin procedure isFull()


 If REAR equals to MAXSIZE. Return “QUEUE IS FULL”
 Else, Return “QUEUE IS NOT FULL”
Peek() operation in Queue

 Begin procedure Peek()


 Check if the queue is empty and return “QUEUE IS EMPTY”
 If the queue is not empty, access DATA from FRONT node.
 Data will be accessed with temporary variable.
 END of procedure Peek.
Types of Queues

 There are four different types of queues that are used in different
scenarios. They are:
 1. Simple Queue or Linear Queue
 2. Circular Queue
 3. Priority Queue
 4. Double Ended Queue (or Deque)
Simple Queue or Linear Queue
Circular Queue

CPU Scheduling (Round Robin


Scheduling):
•In operating systems, circular queues
are used in the round-robin scheduling
algorithm to manage processes. Each
process is assigned a fixed time slot,
and after a process is executed for its
time slot, it is moved to the back of the
queue. This continues in a circular
fashion, ensuring that all processes get
an equal share of the CPU time.

Traffic Signal Management:


•Traffic lights at intersections can be
managed using circular queues. Each
direction (e.g., north, south, east, west)
is given a turn to have the green light.
After one direction has its turn, the
system moves on to the next direction
in a circular fashion.
Priority Queue
Double Ended Queue
Applications of Queues

 Queues in operating systems


 While using multiple applications, Dead Locks occurs in the system
leading to response delay.
 At that instance, OS utilize queues to maintain multiple processes
until their execution.
 Queue data structures is used in printers to maintain the order of
pages while printing.
 Applications like Domino’s, Swiggy and Zomato uses a Queue for
maintaining food order status.
Linked Lists
Linked List

 A linked list is a linear data structure that includes a series of connected


nodes.
 Here, each node stores the data and the address of the next node.
 For example,

 The address of the first node a special name called HEAD. Also, the last node
in the linked list can be identified because its next portion points to NULL.
 Linked lists can be of multiple types: singly, doubly, and circular linked
list. In this article, we will focus on the singly linked list.
Terminologies of Linked List
 Linked List is a linear data structure, in which elements are not stored at
a contiguous location, rather they are linked using pointers. Linked List
forms a series of connected nodes, where each node stores the data
and the address of the next node.

 Node Structure: A node in a linked list typically consists of two


components:
 Data: It holds the actual value or data associated with the node.
 Next Pointer or Reference : It stores the memory address (reference)
of the next node in the sequence.
Linked List

 We want to store a list of numbers : 23,54,78,90

 In an array, elements are stored in consecutive memory locations.


 That is why Array is the sequential representation of list
Linked List
 We want to store a list of numbers : 23,54,78,90

 You can see there is a pointer HEAD to the first node of the list
 Here the nodes are scatter in the memory locations but still
connected with each other.
 The link part of the each node contains the address of the next node.
First node contain the address of second node and second node
contains the address of third node like wise.
Types of Linked List

 There are mainly three types of linked lists:


1. Singly linked list
2. Doubly linked list
3. Circular linked list
Singly Linked List
 Singly Linked List is a type of linked list where each node has two
parts: data and next pointer.
 The data part stores the information and the next pointer points to
the address of the next node of the linked list.
 The next pointer of the last node stores null as it is the last node of
the linked list and there is no next node.
 Traversal of items can be done in the forward direction only due to
the linking of every node to its next node.
Doubly Linked List
 Doubly Linked List is a type of linked list where each node has three
parts: data, next pointer and previous pointer.
 The data part stores the information, the next pointer points to
the address of the next node of the linked list and the previous
pointer points to the previous node address of the linked list.
 The next pointer of the last node and the previous pointer of the first
node stores null.
 Traversal of items can be done in the forward direction as well as
backward direction due to the linking of every node to its next
node as well as the previous node.
Circular Linked List
 A circular linked list is a type of linked list in
which the first and the last nodes are also
connected to each other to form a circle.
 There are basically two types of circular linked
list:
Circular Singly Linked List
 Here, the address of the last node consists of
the address of the first node.

Circular Doubly Linked List


 Here, in addition to the last node storing the
address of the first node, the first node
will also store the address of the last node.
Insertion

A node can be added in three ways:

 At the front of the linked list


 At the end of the linked list.
 After a given node or At a specific position.
Insert a Node at the Front/Beginning of
Linked List
 To insert a new node at the front, we create a new node and point its
next reference to the current head of the linked list.
 Then, we update the head to be this new node. This operation is
efficient because it only requires adjusting a few pointers.
Insert a Node at the End of Linked
List
 Inserting at the end involves traversing the entire list until we reach
the last node.
 We then set the last node’s next reference to point to the new node,
making the new node the last element in the list.
Insert a Node after a Given Node in
Linked List
 If we want to insert a new node after a specific node, we first locate
that node.
 Once we find it, we set the new node’s next reference to point to the
node that follows the given node.
 Then, we update the given node’s next to point to the new node. This
requires traversing the list to find the specified node.
Deletion in Linked List

Deleting a node in a Linked List is an important operation and can be


done in three main ways:
 removing the first node
 removing a node in the middle
 removing the last node.
Deletion at beginning (Removal of
first node) in a Linked List
 The idea to remove the first node of linked list is that we have to
stores the current head in a temporary variable (temp)
 And moves the head pointer to the next node
 And then deletes the old head to free memory.
 And finally, returns the new head of the list.
Deletion at end (Removal of last
node) in a Linked List
 To perform the deletion operation at the end of linked list
 we need to traverse the list to find the second last node, then set its
next pointer to null.
 If the list is empty then there is no node to delete or has only one
node then point head to null.
Delete a Linked List node at a given
position
 To delete a linked list node at a given position, we have to starts by
checking edge cases like, if the list is empty (head == NULL) or not,
we have to do nothing.
 After then, check if the position is the first node, then updates the
head to point its next node, this will effectively remove the first node.
 For other positions, traverses the list to find the node (previous node)
just before the target position, then changes the next of previous
node to target’s next node.
 If the target position is greater than the length of given list, it
indicates that the position is not present.
Circular Linked List
 A circular linked list is a type of linked list in
which the first and the last nodes are also
connected to each other to form a circle.
 There are basically two types of circular linked
list:
Circular Singly Linked List
 Here, the address of the last node consists of
the address of the first node.

Circular Doubly Linked List


 Here, in addition to the last node storing the
address of the first node, the first node will
also store the address of the last node.
Representation

In the above code, one, two, and three are the nodes with data items 1,
2, and 3 respectively.
 For node one
next stores the address of two (there is no node before it)
 For node two
next stores the address of three
 For node three
next stores NULL (there is no node after it)
next points to node one
Insertion

We can insert elements at 3 different positions of a circular linked list:


 Insertion at the beginning
 Insertion in-between nodes
 Insertion at the end
Insertion at Beginning

• store the address of the


current first node in
the newNode (i.e. pointing
the newNode to the
current first node)
• point the last node
to newNode (i.e
making newNode as head)
Insertion between 2 nodes

Let's insert newNode after the first


node.
• travel to the node given (let
this node be p)
• point the next of newNode to
the node next to p
• store the address
of newNode at next of p
Insertion at end

• store the address of the head


node to next of newNode
(making newNode the last
node)
• point the current last node
to newNode
• make newNode as the last
node
Deletion

If the node to be deleted is the only node


• free the memory occupied by the node
• store NULL in last
If last node is to be deleted
• find the node before the last node (let it be temp)
• store the address of the node next to the last node in temp
• free the memory of last
• make temp as the last node

11/12/2024 88
If any other nodes are to be
deleted
• travel to the node to be
deleted (here we are deleting
node 2)
• let the node before node 2
be temp
• store the address of the node
next to 2 in temp
• free the memory of 2
key applications of linked lists

 Dynamic Memory Allocation


 Implementing Data Structures like Stacks ,Queues , Graphs, Hash
Tables.
 Efficient Insertions and Deletions
 File Systems

You might also like