Day 2 Double pointers in the Linked List
I was busy with dealing with something else the other day, but I will continue in this blog from now on :)
This time I will talk about another technique often used in a single-linked-list: double pointers.
For example, when I need to check the nth last element in a linked list, I can use this technique to save memory (instead of creating an entire parallel list)
we will use one pointer to iterate through the entire list, but we’ll also move a second pointer delayed n
steps behind the first one. A count
variable can keep track of the position of the current element in the linked list that the tail pointer is pointing to, which is initially set to 1
which is the first element’s position.
nth last pointer = None tail pointer = linked list head count = 1 while tail pointer exists move tail pointer forward increment count if count >= n + 1 if nth last pointer is None set nth last pointer to head else move nth last pointer forward return nth last pointer
Above is the pseudecode for this approach.
The two pointers can move in different speeds.
For example, if we try to find the middle element of a linked list:
fast pointer = linked list head slow pointer = linked list head while fast pointer is not None move fast pointer forward if the end of the linked list has not been reached move fast pointer forward move slow pointer forward return slow pointer