Skip to content

Instantly share code, notes, and snippets.

@alvareztech
Created August 22, 2016 21:36
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alvareztech/41417c2edbca16df34f1157933e97ec0 to your computer and use it in GitHub Desktop.
Save alvareztech/41417c2edbca16df34f1157933e97ec0 to your computer and use it in GitHub Desktop.
Ejemplo básico de Pilas en Java
package tech.alvarez;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Stack<Libro> pila = new Stack<Libro>();
Libro l1 = new Libro("Título 1", "Autor 1");
Libro l2 = new Libro("Título 2", "Autor 2");
Libro l3 = new Libro("Título 3", "Autor 3");
pila.push(l1); // adiciona un libro a la pila
pila.push(l2);
pila.push(l3);
System.out.println(pila.peek().getTitulo()); // el último elemento adicionado
while (!pila.isEmpty()) { // mostrar pila completa
System.out.println(pila.pop().getTitulo()); // extrae un elemento de la pila
}
}
}
package tech.alvarez;
public class Libro {
private String titulo;
private String autor;
public Libro() {
this.titulo = "";
this.autor = "";
}
public Libro(String titulo, String autor) {
this.titulo = titulo;
this.autor = autor;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getAutor() {
return autor;
}
public void setAutor(String autor) {
this.autor = autor;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment