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
Published at
2026-10-15 05:08:04 UTCEvent JSON
{
"id": "96430e5d11b814cf549ba16b237aeb8afe50ed5d068d2c789bdf1baa8831983b",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1792040884,
"kind": 1,
"tags": [
[
"t",
"tip"
]
],
"content": "Learn: Linked list classic: reverse it\n\nInterviewers want your own Node class, not LinkedList\u003cT\u003e. 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.\n\n```csharp\nNode? cur = new Node(1, new Node(2, new Node(3, null))), prev = null;\nwhile (cur != null)\n{\n Node? next = cur.Next; // save it before relinking\n cur.Next = prev;\n prev = cur;\n cur = next;\n}\nConsole.WriteLine($\"{prev!.Value} {prev.Next!.Value} {prev.Next.Next!.Value}\");\n```\n\nIt prints 3 2 1. O(n) time, O(1) memory.\nThe other classic: fast and slow pointers (fast moves 2, slow moves 1) find the middle, or detect a cycle when they meet.\n\nRead more: https://www.geeksforgeeks.org/dsa/linked-list-data-structure/\n\n#tip · TIP-063",
"sig": "a947f8156dd211319305f2744834b8337c425a5a0aa327a1df7909a4e7b0ff0bc7a579bb69fcb2e895aa4cb0650e92b5234b394c3dff898db79d97de95c03834"
}