Types of Logics to solve Linked Lists
Linked Lists problems can be broadly solved using these four techniques:
Reversal of Linked List
It helps in understanding how to rearrange the nodes and links
public void reverseLinkedList(ListNode head) {
ListNode prev = null;
ListNode current = head;
ListNode forw = null;
while(current != null) {
forw = current.next; // Before de-linking, use this as reference
current.next = prev; // Reversing the link
// Moving the assignments
prev = current; // Since the current node link is rearranged, set prev as current node
current = forw; // And current will be processed, so set current as unlinked forw
}
return prev;
}Time Complexity:
O(n), n-> number of nodes in the linked listSpace Complexity:
O(1), no extra space is used.
Problems to be solved:
Reverse Linked List -->
https://leetcode.com/problems/reverse-linked-list/Reverse Linked List II -->
https://leetcode.com/problems/reverse-linked-list-ii/
Two pointer approach
In this approach, two pointers will move forward at different speeds. This is also called as rabbit and tortoise approach.
We have two pointers slow that traverse one node at a time and fast generally traverse two nodes at a time.
But make sure the while loop termination is done correctly
runner should always be able to access the nodes two points away from the current.
Problems to be solved
Finding Middle of Linked Lists --> https://leetcode.com/problems/middle-of-the-linked-list/
Detecting cycle in LinkedList --> https://leetcode.com/problems/linked-list-cycle/
Detecting the start of the cycle in Linked List --> https://leetcode.com/problems/linked-list-cycle-ii/
Get Intersection of Linked List --> https://leetcode.com/problems/intersection-of-two-linked-lists/
Merge Linked List
Merging two linked lists based on a property or a condition.
Merging two sorted lists
Time Complexity:
Because each recursive call increments the pointer to l1 or l2 by one (approaching the dangling null at the end of each list), there will be exactly one call to mergeTwoLists per element in each list. Therefore, the time complexity is linear in the combined size of the lists.
Space Complexity
The first call to mergeTwoLists does not return until the ends of both l1 and l2 have been reached, so n+m stack frames consume O(n+m) space.
Problems to be Solved
Merging two sorted lists --> https://leetcode.com/problems/merge-two-sorted-list
Sentinel/Dummy Node
Last updated