I won’t repeat what the Miguel Angelo well said.
A stack is so called by in abstract concept. It is evident that physically in memory there is no data being stacked anywhere.
A pile or stack is a very efficient data structure precisely because it is quite limited. But this limitation fits very well in various problems.
It is common for you to add elements followed to a list and remove them from the list in the reverse order placed. 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 battery that varies in size. Of course, every time the space available for the elements needs to be increased or reduced, extra processing is required. But this occurs in blocks (usually doubles in size every time the stack is full and the reduction is only done by manual request). When there is size set an addition "costs" only a pointer change and check whether it has not exceeded the battery limit.
A very typical example of a stack is the organisation of data in memory in an application. As blocks of code are executed, each necessary data is placed on the stack. And when the execution of the block ends and it is no longer necessary to store this data for other uses, just move the pointer down (depending on how you are viewing the stack may be up).
The solution of a Tower of Hanoi also uses battery.
Compilers and software that perform expression analysis also use stacks.
More trivial problems can also use batteries. Whenever you have this UEPS feature (last in, first out), the stack should be used. A trivial example is for 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
}
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
Hello. Please see if this helps: http://www.dotnetperls.com/stack
– Andre Calil
Did any response help you more? You can accept one of them with the most correct (green check sign below the score/ voting arrows of the answer). This gives you reputation.
– Maniero