L14 LinkedList
L14 LinkedList
2
Linked Lists
• Memory efficient DLL
• Instead of storing front & back pointers, can we do better?
• Store pointer difference calculated using XOR
3
Linked Lists: Cycle in a Singly LL
• Check whether a singly LL has a cycle or not?
• Sol A: Brute Force: pointer addresses comparison O(n2)
• Sol B: hashing
• Sol C: Memoryless & efficient solution in O (n): Floyd Algo
• Floyd Cycle Finding Algo: Hare and tortoise race in a track having
cycle.
4
5
Linked List : Interview Questions
• Q1: Find middle of a single LL
• Sol A: Use hash table: O (n)
• Sol B:
concept of Floyd cycle algo?
Use two pointers, one moves at the double speed of
other
6
Linked List : Interview Questions
• Q 2: Find nth node from the last in one scan
• Maintain two pointers;
one pointer always remains n-1 nodes before second
pointer;
7
Next Class Questions
• Check if a singly LL is palindrome or not?
• Generate clone of a singly LL, each node also having a
pointer to a random node in the LL.