Join Nostr
2026-10-15 05:08:04 UTC

codementor on Nostr: Learn: Linked list classic: reverse it Interviewers want your own Node class, not ...

Learn: Linked list classic: reverse it

Interviewers want your own Node class, not LinkedList<T>. Walk the list and point each node back to the one before it. Save the next node first, or you lose the rest of the list.

```csharp
Node? cur = new Node(1, new Node(2, new Node(3, null))), prev = null;
while (cur != null)
{
Node? next = cur.Next; // save it before relinking
cur.Next = prev;
prev = cur;
cur = next;
}
Console.WriteLine($"{prev!.Value} {prev.Next!.Value} {prev.Next.Next!.Value}");
```

It prints 3 2 1. O(n) time, O(1) memory.
The other classic: fast and slow pointers (fast moves 2, slow moves 1) find the middle, or detect a cycle when they meet.

Read more: https://www.geeksforgeeks.org/dsa/linked-list-data-structure/

#tip · TIP-063