codementor on Nostr: Learn: Stack What: last in, first out. Push adds on top (amortized O(1): usually ...
Learn: Stack
What: last in, first out. Push adds on top (amortized O(1): usually instant, sometimes the stack has to grow), Pop takes from the top in O(1).
Use it when: you must undo or go back: undo in an editor, the browser back button, matching brackets, depth-first search.
```csharp
var pairs = new Dictionary<char, char> { [')'] = '(', [']'] = '[' };
var stack = new Stack<char>();
bool ok = true;
foreach (char c in "([])")
if (!pairs.ContainsKey(c)) stack.Push(c);
else ok &= stack.Count > 0 && stack.Pop() == pairs[c];
Console.WriteLine(ok && stack.Count == 0);
```
It prints True: every closing bracket matched the last open one.
Read more:
https://www.geeksforgeeks.org/dsa/stack-data-structure/#tip · TIP-027
Published at
2026-10-14 07:37:57 UTCEvent JSON
{
"id": "dda4a29a9d435d8d9b427e1a9cfd65b8996c370b75cae1f91f7b1f5bf2339e40",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1791963477,
"kind": 1,
"tags": [
[
"t",
"tip"
]
],
"content": "Learn: Stack\n\nWhat: last in, first out. Push adds on top (amortized O(1): usually instant, sometimes the stack has to grow), Pop takes from the top in O(1).\nUse it when: you must undo or go back: undo in an editor, the browser back button, matching brackets, depth-first search.\n\n```csharp\nvar pairs = new Dictionary\u003cchar, char\u003e { [')'] = '(', [']'] = '[' };\nvar stack = new Stack\u003cchar\u003e();\nbool ok = true;\nforeach (char c in \"([])\")\n if (!pairs.ContainsKey(c)) stack.Push(c);\n else ok \u0026= stack.Count \u003e 0 \u0026\u0026 stack.Pop() == pairs[c];\nConsole.WriteLine(ok \u0026\u0026 stack.Count == 0);\n```\n\nIt prints True: every closing bracket matched the last open one.\n\nRead more: https://www.geeksforgeeks.org/dsa/stack-data-structure/\n\n#tip · TIP-027",
"sig": "d8721bc7d67c82d977e3f5e488c2a279cfb16657cfc2bbac7432fadd525b0300b1c3f0148ca1b86aa12a6dd7584f9656584f4aa4ff4cace3445f2836ed8e1d36"
}