Mental Model
A stack adds new items only on top, like stacking plates one on another.
Analogy: Imagine a stack of plates in a kitchen. You always put a new plate on top, never in the middle or bottom.
Top -> null
Top -> null
Top -> [1] -> null
Top -> [2] -> [1] -> null
Top -> [3] -> [2] -> [1] -> null
Top -> 3 -> 2 -> 1 -> null
using System; public class StackNode { public int Data; public StackNode Next; public StackNode(int data) { Data = data; Next = null; } } public class Stack { private StackNode Top; public Stack() { Top = null; } public void Push(int value) { StackNode newNode = new StackNode(value); newNode.Next = Top; // link new node to current top Top = newNode; // update top to new node } public void PrintStack() { StackNode current = Top; while (current != null) { Console.Write(current.Data + " -> "); current = current.Next; } Console.WriteLine("null"); } } public class Program { public static void Main() { Stack stack = new Stack(); stack.Push(1); stack.Push(2); stack.Push(3); stack.PrintStack(); } }
newNode.Next = Top; // link new node to current topTop = newNode; // update top to new nodeTop = newNode; // update top to new node
Push operation do in a stack?stack in C#?Push() to add elements.Push with the value inside parentheses: stack.Push(10);Stack<int> stack = new Stack<int>();
stack.Push(5);
stack.Push(10);
stack.Push(15);
Console.WriteLine(string.Join(", ", stack));Stack<string> stack = new Stack<string>();
stack.Push "hello";
stack.Push("world");stack.Push "hello"; missing parentheses.stack.Push("hello");Stack<int> stack = new Stack<int>();
for (int i = 1; i <= 3; i++)
{
stack.Push(i * 2);
}
stack.Push(10);
stack.Push(stack.Pop() + 5);
Pass the test and this pattern moves unknown