Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

Looking ahead one step

In an array, you can compare a value with the one right after it by index. A linked list has no index math. Instead, when you are standing on the current node, the node immediately after it is its next pointer.

So you can compare the current value with the next node's value directly, like checking whether the person ahead of you in a queue is shorter.

Current value: is the number in the node you stand on.
Next node's value: is the number in the node just ahead.
Check if [2, 5, 4] is sorted
2
0
5
1
4
2
curr

The pointer is on 2, and the next node holds 5. 2 is at most 5, so the order holds. Advance.

Move 1 of 2

Guarding the last node

When you stand on the last node, its next pointer is null, and trying to read a value from null is a crash. To safely compare every adjacent pair, make the loop condition require both the current node and the node after it.

The loop then stops as soon as you reach the last node.

Require both nodes: so the next node is never null inside the loop.
Empty or one node: never enters the loop, correctly answering yes.
In code
curr = head
while curr and curr.next:
    if curr.val > curr.next.val:
        return False
    curr = curr.next
return True