Linked List - 1
Linked List - 1
Linked List - 1
Today’s checklist:
Limitations of Array
Introduction to Linked Lis
Displayin
Insert in Linked Lis
Limitatio
Delete in Linked Lis
Delete Node in a Linked List (Leetcode-237
Middle of Linked List (Leetcode-876
Limitations of Arrays
Fixed Size: Most arrays have a fixed size, meaning you need to know the number of elements in advance.
This can be a limitation when the size of the data is dynamic and unknown beforehand.
Contiguous Memory Allocation: Elements in an array are stored in contiguous memory locations. This can
lead to fragmentation and might make it difficult to find a large enough block of memory for the array.
Inefficient Insertions and Deletions: Inserting or deleting elements in the middle of an array requires shifting
all subsequent elements, which can be inefficient. The time complexity for these operations is O(n), where n
Wastage of Memory: If you allocate more space than needed for an array, you may end up wasting
memory. This is particularly problematic when the array size is predetermined to accommodate the worst-
case scenario.
Homogeneous Data Types: Arrays typically store elements of the same data type. This can be limiting when
you need to store elements of different types.
Memory Fragmentation: The contiguous memory allocation can lead to memory fragmentation, making it
It is basically chains of nodes, each node contains information such as data and a pointer to the next node in
the chain. In the linked list there is a head pointer, which points to the first element of the linked list, and if the list
Java
C++ &+ DSA
DSA
Why linked list data structure needed?
Dynamic Data structure: The size of memory can be allocated or de-allocated at run time based on the
operation insertion or deletion
Ease of Insertion/Deletion: The insertion and deletion of elements are simpler than arrays since no elements
need to be shifted after insertion and deletion, Just the address needed to be updated
Efficient Memory Utilization: As we know Linked List is a dynamic data structure the size increases or
decreases as per the requirement so this avoids the wastage of memory.
Implementation: Various advanced data structures can be implemented using a linked list like a stack,
queue, graph, hash maps, etc.
Java
C++ &+ DSA
DSA
class Node {
public:
int data;
Node* next;
};
LinkedList Class:
class LinkedList {
private:
Node* head;
public:
LinkedList() : head(nullptr) {}
};
Add Nodes:
If the list is empty, create a new node and set it as the head
Otherwise, traverse to the end of the list and add a new node.
if (head == nullptr) {
head = newNode;
} else {
current = current->next;
current->next = newNode;
Displaying
Once, we have created the linked list, we would like to see the elements inside it. Displaying a linked list involves
iterating through its nodes and printing their data. This can also be done recursively as shown in the code
below.
Java
C++ &+ DSA
DSA
Code:
#include <iostream>
class Node {
public:
int data;
Node* next;
};
head = head->next;
if (head == nullptr)
return;
displayLinkedListRecursive(head->next);
int main() {
displayLinkedListIterative(head);
displayLinkedListRecursive(head);
return 0;
Explanation:
Iterative Display:
Print the data of each node and move the pointer to the next node
Java
C++ &+ DSA
DSA
Recursive Display:
Base case ensures termination when the end of the list is reached.
Iterative Display:
Time Complexity: O(n) - where 'n' is the number of nodes in the linked list. The algorithm iterates through each
node once.
Space Complexity: O(1) - uses a constant amount of extra space, regardless of the size of the linked list.
Recursive Display:
Time Complexity: O(n) - where 'n' is the number of nodes in the linked list. Similar to the iterative approach,
each node is visited once, but the recursive call stack contributes to the time complexity.
Space Complexity: O(n) - due to the recursive call stack. The maximum depth of the recursion is 'n',
if(head == null)
return;
display(head->next);
cout<<head.val<” “;
Explanation:
The given function is a recursive function that traverses the linked list using a recursive call (display(head-
>next)) before printing the value of the current node (cout<<head.val<<" ")
The base case (if(head == null) return;) ensures that the recursion stops when the end of the linked list is
reached
As the recursion unfolds, the values of the nodes are printed in reverse order, starting from the last node and
Java
C++ &+ DSA
DSA
Length of Linked List
Code:
#include <iostream>
class Node {
public:
int data;
Node* next;
};
int length = 0;
length++;
head = head->next;
return length;
if (head == nullptr)
return 0;
return 1 + findLengthRecursive(head->next);
int main() {
return 0;
Java
C++ &+ DSA
DSA
Iterative Method:
Time Complexity: O(n) - where 'n' is the number of nodes in the linked list. In the worst case, it needs to traverse
Recursive Method:
Time Complexity: O(n) - where 'n' is the number of nodes in the linked list. Similar to the iterative approach, it
Space Complexity: O(n) - due to the recursive call stack. The maximum depth of the recursion is 'n',
The insertion operation can be performed in three ways. They are as follows…
Code:
#include <iostream>
class Node {
public:
int data;
Node* next;
};
newNode->next = head;
return newNode;
if (head == nullptr) {
return newNode;
Java
C++ &+ DSA
DSA
Node* current = head;
current = current->next;
current->next = newNode;
return head;
if (position == 1) {
newNode->next = head;
return newNode;
current = current->next;
if (current == nullptr) {
return head;
newNode->next = current->next;
current->next = newNode;
return head;
head = head->next;
int main() {
displayLinkedList(head);
displayLinkedList(head);
Java
C++ &+ DSA
DSA
// Insert at Specific location
displayLinkedList(head);
return 0;
Java
C++ &+ DSA
DSA
Code:
#include <iostream>
class Node {
public:
int data;
Node* next;
};
if (head == nullptr) {
return nullptr;
delete head;
return newHead;
if (head == nullptr) {
return nullptr;
if (head->next == nullptr) {
delete head;
return nullptr;
current = current->next;
delete current->next;
current->next = nullptr;
return head;
if (head == nullptr) {
return nullptr;
if (head->data == value) {
Java
C++ &+ DSA
DSA
Node* newHead = head->next;
delete head;
return newHead;
current = current->next;
if (current->next == nullptr) {
cout << "Node with value " << value << " not found." <<
endl;
return head;
current->next = current->next->next;
delete temp;
return head;
head = head->next;
int main() {
head = deleteFromBeginning(head);
displayLinkedList(head);
head = deleteFromEnd(head);
displayLinkedList(head);
displayLinkedList(head);
return 0;
Certainly! Below is a C++ code snippet that demonstrates deletion operations in a linked list:
Java
C++ &+ DSA
DSA
CPP
Copy code
#include <iostream>
class Node {
public:
int data;
Node* next;
};
if (head == nullptr) {
return nullptr;
delete head;
return newHead;
if (head == nullptr) {
return nullptr;
if (head->next == nullptr) {
delete head;
return nullptr;
current = current->next;
delete current->next;
current->next = nullptr;
return head;
if (head == nullptr) {
return nullptr;
Java
C++ &+ DSA
DSA
if (head->data == value) {
delete head;
return newHead;
current = current->next;
if (current->next == nullptr) {
cout << "Node with value " << value << " not found." <<
endl;
return head;
current->next = current->next->next;
delete temp;
return head;
head = head->next;
int main() {
head = deleteFromBeginning(head);
displayLinkedList(head);
head = deleteFromEnd(head);
displayLinkedList(head);
displayLinkedList(head);
return 0;
Java
C++ &+ DSA
DSA
Explanation:
ad usting pointers.
j
You are given the node to be deleted node. You will not be given access to the first node of head .
All the values of the linked list are uni ue, and it is guaranteed that the given node node is not the last node in
q
D elete the given node. ote that by deleting the node, we do not mean removing it from memory. e mean
N W :
T he value of the given node should not exist in the linked list
T he number of nodes in the linked list should decrease by one
A ll the values before node should be in the same order
A ll the values after node should be in the same order.
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling
your function.
Java
C++ &+ DSA
DSA
Code:
class Solution {
public:
node->val = node->next->val;
node->next = node->next->next;
};
Time complexity: O(1) - Constant time complexity. The deletion operation involves updating the value of the
given node with the value of its next node and then updating the next pointer to skip the next node. These
operations are constant time.
Space complexity: O(1) - Constant space complexity. The algorithm uses only a constant amount of extra
space, regardless of the size of the input linked list.
If there are two middle nodes, return the second middle node.
Output: [3,4,5]
Java
C++ &+ DSA
DSA
Code:
class Solution {
public:
slow = slow->next;
fast = fast->next->next;
return slow;
};
Time complexity: O(n), where n is the number of nodes in the linked list. The algorithm iterates through the
linked list with two pointers (slow and fast), and in each iteration, the fast pointer moves two steps while the
slow pointer moves one step.
Space complexity: O(1). The algorithm uses only a constant amount of extra space for the two pointers,
regardless of the size of the input linked list.
Output: [1,2,3,5]
Java
C++ &+ DSA
DSA
Code:
class Solution {
public:
slow->next = slow->next->next;
return head;
};
Time complexity: O(n), where n is the number of nodes in the linked list. The algorithm uses two pointers to
traverse the linked list. The first loop advances the fast pointer by n nodes, and then the second loop advances
both pointers until the fast pointer reaches the end.
Space complexity: O(1). The algorithm uses only a constant amount of extra space for the two pointers,
regardless of the size of the input linked list.
Intersection of two Linked Lists (Leetcode-160)
Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If
the two linked lists have no intersection at all, return null.
For example, the following two linked lists begin to intersect at node c1:
Explanation: The intersected node s value is (note that this must not be if the two lists intersect)
' 2 0 .
From the head of A, it reads as 1, ,1, , . From the head of B, it reads as , , . There are nodes before the
[ 9 2 4] [3 2 4] 3
Java
C++ &+ DSA
DSA
Code:
class Solution {
public:
while(a != b){
return a;
};
Time complexity: O(m + n), where m and n are the lengths of the two linked lists. The pointers traverse the
linked lists once, and the loop continues until either the intersection is found or both pointers reach the end.
Space complexity: O(1). The algorithm uses only a constant amount of extra space for the two pointers (a and
b), regardless of the size of the linked lists.
Linked List Cycle (Leetcode-141)
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously
following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is
connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Java
C++ &+ DSA
DSA
Code:
class Solution {
public:
slow_pointer = slow_pointer->next;
fast_pointer = fast_pointer->next->next;
if (slow_pointer == fast_pointer) {
return true;
return false;
};
Time complexity: O(n), where n is the number of nodes in the linked list. The algorithm has at most two pointers
traversing the linked list, and the loop will continue until the fast pointer reaches the end or the two pointers
meet in a cycle.
Space complexity: O(1). The algorithm uses only a constant amount of extra space for the two pointers
(slow_pointer and fast_pointer), regardless of the size of the linked list.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously
following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is
connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Java
C++ &+ DSA
DSA
Code:
class Solution {
public:
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
slow = head;
slow = slow->next;
fast = fast->next;
return slow;
return nullptr;
};
Time complexity: O(n), where n is the number of nodes in the linked list. The algorithm uses two pointers, slow
and fast, to traverse the linked list. In the worst case, it needs to iterate through the entire linked list once.
Space complexity: O(1). The algorithm uses only a constant amount of extra space for the two pointers (slow
and fast), regardless of the size of the linked list. It doesn't use any additional data structures that scale with the
input size.
Java
C++ &+ DSA
DSA
THANK
YOU !