I will not repeat what the Miguel Angelo well said.
A stack is called so by in abstract concept. Obviously physically in memory there is no data being piled anywhere.
A stack or stack is a very efficient data structure precisely because it is quite limited. But that limitation fits very well into various problems.
You often need to add elements to a list in a row and remove them from the list in reverse order. This way it is very easy to manipulate the insertion and removal of elements.
This becomes especially favorable if you have a defined stack size that always fits all the elements that need to be placed. But nothing prevents you from having a stack that varies in size. Of course, every time that the space available for the elements needs to be increased or reduced, extra processing is required. But this occurs in blocks (usually doubling every time the stack is full and the reduction is only done by manual request). When there is a defined size an addition "costs" only a pointer change and verification if the stack boundary has not broken.
Afairlytypicalexampleofastackis organization of data in memory in an application. As blocks of code are executed, every necessary data is placed on the stack. And when the execution of the block ends and it is no longer necessary to save that data for other uses, simply move the pointer down (depending on how you are looking the stack can be up).
The solution to a Tower of Hanoi problem also uses a stack.
Compilers and software that do expression analysis also use batteries.
More trivial problems can also be used with batteries. Whenever you have this UEPS (last-in, first-out) feature, the battery should be used. A trivial example is for functionality of undo .
Example:
using System;
using System.Collections.Generic;
class Program {
static Stack<int> MontaPilha() {
var pilha = new Stack<int>(); //Cria a pilha que vai guardar ints
pilha.Push(3261); //manda o primeiro elemento para a pilha
pilha.Push(1352); //vai mais um elemento ficando do seu topo
pilha.Push(723); //sucessivamente
pilha.Push(1234);
return pilha;
}
static void Main() {
var pilha = MontaPilha();
foreach (int i in pilha) {
Console.WriteLine(i); //acesa cada inteiro varrendo toda a pilha
}
Console.WriteLine(pilha.Pop()); //retira o elemento mais recente colocado na pilha. no exemplo passará ter apenas 3 elementos. Vai imprimir 1234
Console.WriteLine(pilha.Peek()); //pega o elemento mais recente/topo sem retirá-lo. Vai imprimir 123
pilha.Clear(); //limpa todos os elementos da pilha
Console.WriteLine(pilha.Count); //vai imprimir 0
}
}
See working on .NET Fiddle . And in the Coding Ground (I post later, technical problems). Also I put it in GitHub for future reference .