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 list

  • Space Complexity: O(1), no extra space is used.

Problems to be solved:

Drawing

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.

Time Complexity:

O(n)O(n) n--> number of nodes in LinkedList

Space Complexity

O(1)O(1) auxillary space. Didn't use any new structure to store things

Problems to be solved

Drawing

Merge Linked List

Merging two linked lists based on a property or a condition.

Merging two sorted lists

Time Complexity

Because exactly one of l1 and l2 is incremented on each loop iteration, the while loop runs for a number of iterations equal to the sum of the lengths of the two lists. All other work is constant, so the overall complexity is linear.

Problems to be Solved

Sentinel/Dummy Node

Last updated