---
description: Last In First Out (LIFO)
---

# Stack

The last item to be inserted into a stack is the first one to be deleted from it.

* **Example:** A stack of trays on a table, the tray at the top of the stack is the first item to be moved if you require a tray from that stack.

{% embed url="https://3.bp.blogspot.com/-ZTPyluNn8oU/XlkES_014qI/AAAAAAAAHRs/fG18AQEHxAwtzXiM7nKbssA3sl3uPVAtQCLcBGAsYHQ/s1600/0_SESFJYWU5a-3XM9m.gif" %}

<details>

<summary>Stack : Example</summary>

* Non-Generic Stack

```csharp
using System;
using System.Collections;

public class NonGenericStackExample {
    public static void Main() {
	Console.WriteLine("Non-Generic Stack Example\n");
	var myStack = new Stack();
	myStack.Push("Hello,");
	myStack.Push("World!");
	Console.WriteLine("Items in the Simple Stack: ");
	foreach (var item in myStack) {
		Console.WriteLine("- " + item + " ");
	}
    }
}
```

* Generic Stack

```csharp
using System;
using System.Collections.Generic;

public class GenericStackExample {
    public static void Main() {
	Console.WriteLine("Generic Stack Example\n");
	Stack<string> gStack = new Stack<string>();
	gStack.Push("One");
	gStack.Push("Two");
	gStack.Push("Three");
	gStack.Push("Four");
	gStack.Push("Five");
	Console.WriteLine("Items in the Generic Stack: ");
	foreach (var item in gStack) {
	    Console.WriteLine("- " + item + " ");
	}

	Console.WriteLine("Count: " + gStack.Count);
	Console.WriteLine("Contains(): " + gStack.Contains("One"));
	Console.WriteLine("Peek(): " + gStack.Peek());
	Console.WriteLine("Pop(): " + gStack.Pop());
	foreach (var item in gStack) {
	    Console.WriteLine("- " + item + " ");
	}

	Console.WriteLine("Copy of gStack also reversing the order");
	Stack<string> cgStack = new Stack<string>(gStack.ToArray());
	foreach (var cItem in cgStack) {
	    Console.WriteLine("- " + cItem + " ");
	}

	Console.WriteLine("Copy of gStack");
	string[] array = new string[gStack.Count * 2];
	gStack.CopyTo(array, gStack.Count);
	Stack<string> cgStack2 = new Stack<string>(array);
	foreach (var cItem in cgStack2)	{
	    Console.WriteLine("- " + cItem + " ");
	}

	Console.Write("Clear():");
	cgStack.Clear();
    }
}
```

</details>

### Applications

* undo/redo functionality
* word reversal
* stack backward/forward on browsers
* backtracking algorithms
* bracket verification
