Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

LINKED LIST

Insert Node at beginning of Delete a node from last of linked list


Linked List Node *deleteLast(Node *list)
{
Node* insertAtFirst(Node* list, int Node* curr = list;
newValue) Node* prev = NULL;
{ while(curr->next != NULL)
Node * temp = new {
Node(newValue); prev=curr;
temp->next = list; curr=curr->next;
list = temp;
return list; }
} prev->next=curr->next;
delete curr;
return list;
}

Count nodes of linked list Search in a Linked List


int length(Node *head) int searchInLinkedList(Node<int> *head, int k)
{ {
if(head==NULL) return 0; Node <int> *temp=head;
int cnt =1; while(temp!=NULL)
while(head->next!=NULL) {
{ if(temp->data==k)
head=head->next; {
cnt++; return 1;
} }
return cnt; temp=temp->next;
} }
return 0;
}

Insert at end of Doubly Linked Delete Last Node of a Doubly Linked List
List
Node * deleteLastNode(Node *head)
Node * insertAtTail(Node *head,
int k) {
{
if(head==NULL) if(head==NULL || head->next==NULL)
return new Node(k); return NULL;
Node * temp = head;
Node* curr = new Node(k); Node* temp =head;
while(temp->next!=NULL)
{ Node*prev=NULL;
temp=temp->next;
} while(temp->next!=NULL)
temp->next= new Node(k);
curr->prev=temp; {
return head;
} prev =temp;

Time Complexity: O(n) temp=temp->next;

Space Complexity: O(1) }

prev->next=NULL;

delete temp;

return head;

Time Complexity: O(1) Removing the


head of a doubly linked list is a quick
operation, taking constant time because
it only involves updating references.

Space Complexity: O(1) Deleting the head


also has minimal memory usage, using a
few extra pointers without regard to the
list’s size

Find middle element in a Linked


List Node *findMiddle(Node
Node *findMiddle(Node *head) *head)
{
Node *temp =head; {
int cnt =0;
while(temp!=NULL) if(head==NULL) return
{ NULL;
cnt++;
temp=temp->next;
} Node* temp =head;
Node*curr =head;
for(int i=0 ;i<cnt/2; i++) Node* curr =head;
{
curr=curr->next; while(temp!=NULL &&
} temp->next!=NULL)
return curr;
} {

Time Complexity: O(n)


temp=temp->next->next;
Space Complexity: O(1)
curr=curr->next;

return curr;

Time Complexity: O(N)

Space Complexity: O(1)

REVERSE A LINKED LIST Recursive way


(ITERATIVE METHOD)
Node* reverseLinkedList(Node *head)
Node* reverseLinkedList(Node
*head) {

{ if(head==nullptr||head->next==nullptr)

Node* curr = head; return head;

Node* prev = NULL; Node* prev=


reverseLinkedList(head->next);
Node * temp; Node * temp =head->next;

while(curr!=NULL) temp->next=head;

{ head->next=nullptr;

temp=curr->next; return prev;

curr->next=prev; }

prev=curr; Time Complexity: O(n)

curr=temp; Space Complexity: O(n) (due to the


recursive call stack)
}

return prev;

Since we are iterating only


once through the list and
achieving a reversed list. Thus,
the time complexity is O(N)
where N is the number of
nodes present in the list.

Space Complexity:

To perform given tasks, no


external spaces are used
except three-pointers. So,
space complexity is O(1).

Cycle Detection in a Singly Linked Floyd cycle


List bool detectCycle(Node *head)
# include<bits/stdc++.h> {
using namespace std; if(head==NULL) return false;
bool detectCycle(Node *head) Node* slow = head;
{ Node* fast = head;
if(head==NULL) while(fast!=NULL &&
return false; fast->next!=NULL)
set<Node*>st; {
while(head!=NULL) slow=slow->next;
{ fast = fast->next->next;
if(st.find(head)!=st.end()) return true; if(slow==fast)
st.insert(head); {
head=head->next; return true;
} }
return false; }
}
return false;
Time Complexity: O(N)
}
Reason: Entire list is iterated once.
Time Complexity: O(N)
Space Complexity: O(N)
Reason: In the worst case, all the
Reason: All nodes present in the list nodes of the list are visited.
are stored in a hash table.
Space Complexity: O(1)

Reason: No extra data structure is


used.

Starting point of loop in a Linked List


Slow and Fast Pointer Method
# include<bits/stdc++.h>
Node *firstNode(Node *head)
using namespace std;
{
Node *firstNode(Node *head)
{ if (head == NULL)

if(head==NULL) return NULL; return NULL;

set<Node*>st; Node *slow = head;

while(head!=NULL) Node *fast = head;

{ Node* entry = head;

if(st.find(head)!=st.end()) return while (fast != NULL && fast->next != NULL)


head;
{
st.insert(head);
slow = slow->next;
head=head->next;
fast = fast->next->next;
}
if (slow == fast)
return NULL;
{
}
while(slow!=entry)
Time Complexity: O(N)
{
Reason: Iterating the entire list once.
slow = slow->next;
Space Complexity: O(N)
entry =entry->next;
Reason: We store all nodes in a hash
table. }

return slow;

return NULL;

}
Check if given Linked List is Check if given Linked List is Palindrome
Palindrome
bool isPalindrome(Node *head) Node* reverse(Node* head)
{ {
vector<int>ans; if (head == nullptr || head->next == nullptr)
while(head!=NULL) {
{ return head;
ans.push_back(head->data); }
head = head->next; Node* prev = nullptr;
} Node* curr = head;
int n = ans.size(); Node* temp;
for(int i=0;i<n/2;i++) while (curr != nullptr)
{ {
if(ans[i]!=ans[n-1-i]) temp = curr->next;
{ curr->next = prev;
return false; prev = curr;
} curr = temp;
} }
return true; return prev;
} }
bool isPalindrome(Node* head)
Time Complexity: O(N) {
if (head == nullptr)
Reason: Iterating through the list to {
store elements in the array. return false;
}
Space Complexity: O(N)
Node* slow = head;
Reason: Using an array to store list
Node* fast = head;
elements for further computations.
while (fast->next != nullptr && fast->next->next
!= nullptr)
{ slow = slow->next;
fast = fast->next->next;
}
slow->next = reverse(slow->next);
Node* dummy = head;
while (slow->next != nullptr)
{
if (slow->next->data != dummy->data)
{
return false;
}
slow = slow->next;
dummy = dummy->next;
}
return true;
}

Time Complexity: O(N/2)+O(N/2)+O(N/2)

Reason: O(N/2) for finding the middle element,


reversing the list from the middle element, and
traversing again to find palindrome respectively.

Space Complexity: O(1)

Delete Kth Node From End Delete Kth Node From End
Node* removeKthNode(Node* head, int K) Node* removeKthNode(Node* head, int
{ K)
if (K <= 0 || head == nullptr) {
{ Node * start =new Node();
return head; start->next=head;
} Node * fast = start;
int length = 0; Node*slow = start;
Node* temp = head; for(int i=1;i<=K;i++)
while (temp != nullptr) {
{ fast=fast->next;
length++; }
temp = temp->next; while(fast->next!=NULL)
} {
if (K > length) slow =slow->next;
{ fast=fast->next;
return head; }
} slow->next=slow->next->next;
int indexToRemove = length - K; return start->next;
if (indexToRemove == 0) }
{
Node* newHead = head->next; Time Complexity: O(N)
delete head;
return newHead; Space Complexity: O(1)
}
temp = head;
for (int i = 0; i < indexToRemove - 1; ++i)
{
temp = temp->next;
}
Node* toRemove = temp->next;
temp->next = temp->next->next;
delete toRemove;
return head;
}
T=O(N)+O(N)
S=O(1)

Delete Middle Node


Node* deleteMiddle(Node* head)
{
if(head==NULL || head->next ==NULL)
return NULL;
Node* fast = head;
Node* slow = head;
Node* prev =NULL;
while(fast!=NULL && fast->next!=NULL)
{
prev=slow;
slow = slow ->next;
fast=fast->next->next;
}
if(prev!=NULL)
{
prev->next=slow->next;
delete slow;
}
else
{
head=head->next;
delete slow;
}
return head;
}

SORT LINKED LIST SORT LINKED LIST


Node * merge(Node* left, Node* Node* sortList(Node* head)
right) {
{ if(head==NULL || head ->next==NULL)
Node* dummy = new Node(-1); return head;
Node *curr =dummy; Node* slow =head;
if(left ==NULL) return right; Node* fast = head;
if(right ==NULL) return left; while(fast->next!=NULL &&
while (left!=NULL && fast->next->next!=NULL)
right!=NULL) {
{ slow =slow->next;
if(left->data<right->data) fast=fast->next->next;
{ }
curr->next = left; Node * left =head;
curr = curr->next; Node* right = slow->next;
left=left->next; slow->next=NULL;
} left = sortList(left);
else right = sortList(right);
{ Node* result = merge(left,right);
curr->next=right; return result;
curr=curr->next; }
right = right->next;
}
}
while(left!=NULL)
{
curr->next = left;
curr = curr->next;
left=left->next;
}
while(right !=NULL)
{
curr->next=right;
curr=curr->next;
right = right->next;
}
dummy=dummy->next;
return dummy;
}

Sort linked list of 0s 1s 2s Intersection of Two Linked Lists


Node* sortList(Node *head) Brute force approach
{ Node* findIntersection(Node *firstHead, Node
int zero =0; *secondHead)
int one =1; {
int two =2; while(secondHead!=NULL)
Node* temp =head; {
while(temp!=NULL) Node*temp=firstHead;
{ while(temp!=NULL)
if(temp->data==0) zero++; {
if(temp->data==1) one++; if (temp==secondHead) return secondHead;
if(temp->data==2) two++; temp=temp->next;
temp=temp->next; }
} secondHead=secondHead->next;
temp= head; }
while ( temp!=NULL) return NULL;
{ }
if(zero!=0)
{
temp->data=0; Time Complexity: O(m*n)
zero--;
} Reason: For each node in list 2 entire lists 1 are
else if (one !=1) iterated.
{
temp->data=1; Space Complexity: O(1)
one--;
Reason: No extra space is used
}
else if (two!=2)
{

temp->data=2;
two--;
}
temp = temp->next;
}
return head;
}

Node* findIntersection(Node *firstHead,


By HASHING Node *secondHead)
{
# include<bits/stdc++.h> int len1=0;
int len2 =0;
using namespace std; Node*temp1= firstHead;
Node*temp2= secondHead;
Node* findIntersection(Node *firstHead,
while( temp1!=NULL)
Node *secondHead)
{
{ len1++;
temp1=temp1->next;
set<Node*> st; }
while (temp2!=NULL)
{
while(firstHead!=NULL) len2++;
temp2=temp2->next;
{ }
temp1=firstHead;
st.insert(firstHead); temp2=secondHead;
int diff = abs(len1-len2);
firstHead=firstHead->next;
while(diff!=0)
} {
if(len1>len2)
while(secondHead!=NULL) {
temp1=temp1->next;
{ }
else temp2=temp2->next;
if(st.find(secondHead)!=st.end()) diff--;
return secondHead; }
while(temp1!=NULL && temp2!=NULL)
secondHead=secondHead->next; {
if(temp1==temp2) return temp1;
} else {
temp1=temp1->next;
return NULL; temp2=temp2->next;
}
}
}
Time Complexity: O(n+m) return NULL;
}
Reason: Iterating through list 1 first takes O(2max(length of list1,length of
O(n), then iterating through list 2 takes list2))+O(abs(length of list1-length of
O(m). list2))+O(min(length of list1,length of list2))
Reason: Finding the length of both lists
Space Complexity: O(n) takes max(length of list1, length of list2)
because it is found simultaneously for
Reason: Storing list 1 node addresses in both of them. Moving the head pointer
unordered_set. ahead by a difference of them. The next
one is for searching.
Space Complexity: O(1)
node* intersectionPresent(node* head1,node* head2) {

node* d1 = head1;

node* d2 = head2;

while(d1 != d2) {

d1 = d1 == NULL? head2:d1->next;

d2 = d2 == NULL? head1:d2->next;

return d1;

Add Two Numbers Delete all occurrences of a given key in a


doubly linked list
Node *addTwoNumbers(Node *num1, Node
*num2) Node * deleteAllOccurrences(Node* head,
{ int k)
Node *dummy = new Node(0); {
Node *temp = dummy; if(head==NULL) return NULL;
int sum = 0; {
int carry = 0; while(head!=NULL && head->data==k)
while (num1 != NULL || num2 != NULL || }
carry != 0) head=head->next;
{ Node* temp=head;
if (num1 != NULL) while(temp!=NULL)
{ {
sum += num1->data; if(temp->data == k)
num1 = num1->next; {
} if(temp->next!=NULL)
if (num2 != NULL) {
{ temp->prev->next=temp->next;
sum += num2->data; temp->next->prev=temp->prev;
num2 = num2->next; delete temp;
} }
sum += carry; else
carry = sum / 10; {
Node *curr = new Node(sum % 10); temp->prev->next=NULL;
temp->next = curr; delete temp;
temp = temp->next; }
sum =0; }
} else
return dummy->next; temp=temp->next;
} }
return head;
Time Complexity: O(max(m,n)). Assume }
that m and n represent the length of l1 and
l2 respectively, the algorithm above iterates
at most max(m,n) times. The time complexity is O(n), and the space
complexity is O(1).
Space Complexity: O(max(m,n)). The length
of the new list is at most max(m,n)+1.

Remove duplicates from a sorted Doubly Find pairs with given sum in DLL
Linked List
Node *removeDuplicates(Node vector<pair<int, int>> findPairs(Node* head, int k)
*head) { {
if (head == nullptr || head->n== nullptr) vector< pair<int,int>> ans;
return head;
Node* temp =head;
Node *temp = head; while(temp->next!=NULL)
{
while (temp->next != nullptr) Node* curr = temp->next;
{
while(curr!=NULL)
if (temp->data == temp->next->data)
{ {
Node *duplicate = temp->next; if(temp->data + curr->data == k)
temp->next = duplicate->next; {
if (temp->next != nullptr)
ans.push_back({temp->data ,curr->data});
{ }
temp->next->prev = temp; curr=curr->next;
} }
delete duplicate;
} temp=temp->next;
else }
{ return ans;
temp = temp->next;
}
}
}

return head;
}

Reverse LL in group of given size K Rotate Linked List


Node* kReverse(Node* head, int k)
{ Node *rotate(Node *head, int k)
if (head== NULL||head->next == NULL) {
return head; if(head == NULL||head->next ==
int length = 1; NULL||k == 0)
Node* temp = head; return head;
while (temp->next != NULL) Node* temp = head;
{ int length = 1;
length++; while(temp->next != NULL)
temp = temp->next; {
} length++;
Node* dummyHead = new Node(0); temp = temp->next;
dummyHead->next = head; }
Node* pre = dummyHead; temp->next = head;
Node* cur; k = k%length;
Node* nex; int end = length-k;
while (length >= k) while(end!=0)
{ {
cur = pre->next; temp = temp->next;
nex = cur->next; end--;
for (int i = 1; i < k; i++) }
{ head = temp->next;
cur->next = nex->next; temp->next = NULL;
nex->next = pre->next; return head;
pre->next = nex; }
nex = cur->next;
} Time Complexity: O(length of list) +
pre = cur; O(length of list – (length of list%k))
length -= k;
} Reason: O(length of the list) for
return dummyHead->next; calculating the length of the list.
} O(length of the list – (length of list%k))
for breaking links.
Time Complexity: O(N)
Space Complexity: O(1)
Reason: Nested iteration with O((N/k)*k) which
makes it equal to O(N).

Space Complexity: O(1)

Flatten A Linked List Clone of linked list


Node *cloneLL(Node *head)
Node* merge(Node* a , Node* b) {
{ Node* temp = head;
Node* temp = new Node(0); while(temp != NULL)
Node* result = temp; {
while(a!=NULL && b!=NULL) Node* newNode = new
{ Node(temp->data);
if(a->data < b->data) newNode->next = temp->next;
{ temp->next = newNode;
temp->child = a; temp = temp->next->next;
a = a->child; }
} Node* itr = head;
else while(itr != NULL)
{ {
temp->child = b; if(itr->random != NULL)
b = b->child; {
} itr->next->random = itr->random->next;
temp = temp->child; }
} itr = itr->next->next;
if(a!=NULL) }
{ Node* dummy = new Node(0);
temp->child = a; itr = head;
} temp = dummy;
if (b != NULL) Node* fast;
{ while(itr != NULL)
temp->child = b; {
} fast = itr->next->next;
return result->child; temp->next = itr->next;
} itr->next = fast;
Node* flattenLinkedList(Node* head) temp = temp->next;
{ itr = fast;
if(head == NULL || head->next == NULL) }
return head; return dummy->next;
Node * curr= }
flattenLinkedList(head->next); T=O(N) S=O(1)
head->next = NULL;
curr->next = NULL;
head = merge(head, curr);
return head;
}
Confusion ho to love babbar ka last me
dekh lo

Time Complexity: O(N), where N is the


total number of nodes present

Reason: We are visiting all the nodes


present in the given list.

Space Complexity: O(1)

Reason: We are not creating new nodes or


using any other data structure.

You might also like