Stack

Last In First Out (LIFO)

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.

Stack : Example
  • Non-Generic Stack

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

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();
    }
}

Applications

  • undo/redo functionality

  • word reversal

  • stack backward/forward on browsers

  • backtracking algorithms

  • bracket verification

Last updated