Linked List Lecture II
Linked List Lecture II
1 2 3 4
Pre-requisites
1. Linked list
Problem I
Return the n-th last element of a singly linked list.
3
Approach I
4
Two Pointer Technique in Linked List
5
Approach II
1 2 3 4 5
6
Simulation
1 2 3 4 5
7
Simulation
1 2 3 4 5
8
Simulation
1 2 3 4 5
9
Simulation
1 2 3 4 5
10
Simulation
1 2 3 4 5
11
Simulation
1 2 3 4 5
12
Simulation
1 2 3 4 5
13
Problem II
Return the middle element of a linked List
14
Approach : Fast and slow Pointers
15
Simulation
16
17
The middle
node
18
Pair Programming
Middle element of a linked list
19
Check Point
Link
20
Floyd’s Cycle Finding Algorithm
21
Initial Problem
Given a linked list, return the node where the cycle begins?
22
Floyd's algorithm consists of two phases and uses two
pointers, usually called tortoise and rabbit.
23
Phase I - Cycle Detection
24
25
Phase 1
26
Phase 1
27
Phase 1
28
Phase 1
29
Phase 1
30
Phase 1
31
Phase 1
32
Phase II - Determine Cycle Entrance
To compute the cycle entrance, let's note that the rabbit has traversed
twice as many nodes as the tortoise, i.e.
33
● we give the tortoise a second chance by slowing down the
rabbit,
○ tortoise = tortoise.next
○ rabbit = rabbit.next
● The tortoise is back at the starting position, and the rabbit
starts from the first intersection point.
Phase 2
35
Phase 2 is over!
Rabbit
36
Back to Initial Problem
Pair Programming
Linked List Cycle
37
Common Pi alls
Can you spot the error?
What if head
return head.val == target is null?
Solution
while fast:
slow = slow.next
fast = fast.next.next
return slow
Solution
47
Practice Questions
● Reverse Linked List
● Partition List
● LRU Cache
48
Resources
● Leetcode Explore Card: has excellent track path with good explanations
● Leetcode Solution (Find the Duplicate Number) : has good explanation
about Floyd’s cycle detection algorithm with good simulation
● Elements of Programming Interview book: has a very good Linked List
Problems set
49
50