Interfaz a Utilizar:
package Pilas_de_Nodos;
/**
* @author Daniel Cataño Restrepo <dasniel199410@gmail.com>
*/
public interface INodeStack<E>{
public boolean isEmpty();
public E peek();
public E pop();
public void print();
public void push(E target);
}
La clase NodeStack
package Pilas_de_Nodos;
/**
* @author Daniel Cataño Restrepo <dasniel199410@gmail.com>
*/
public class NodeStack<E> implements INodeStack<E>{
private NodeStack<E> next;
private E item;
private NodeStack<E> raiz;
public NodeStack(E item){
this.item=item;
}
public NodeStack(NodeStack<E> next){
this.next=next;
}
public NodeStack(E item, NodeStack<E> next){
this.item=item;
this.next=next;
}
public NodeStack<E> getNext() {
return next;
}
public void setNext(NodeStack<E> next) {
this.next = next;
}
public E getItem() {
return item;
}
public void setItem(E item) {
this.item = item;
}
public NodeStack getRaiz() {
return raiz;
}
public void setRaiz(NodeStack raiz) {
this.raiz = raiz;
}
public boolean isEmpty() {
return raiz==null;
}
public E peek() {
E firstElement=raiz.item;
if(!isEmpty()){
if(raiz.next==null)
raiz=null;
else
raiz=raiz.next;
return firstElement;
}
return null;
}
public E pop() {
return raiz.item;
}
public void print() {
System.out.print("[");
for(NodeStack temp=raiz; temp!=null; temp=temp.next){
if(temp.next==null)
System.out.print(temp.item);
else
System.out.print(temp.item+",");
}
System.out.println("]");
}
public void push(E target) {
NodeStack<E> nuevo=new NodeStack<>(target);
if(isEmpty()){
nuevo.next=null;
raiz=nuevo;
}else{
nuevo.next=raiz;
raiz=nuevo;
}
}
}
La clase principal
package Pilas_de_Nodos;
/**
* @author Daniel Cataño Restrepo <dasniel199410@gmail.com>
*/
public class Main {
public static void main(String[] args) {
NodeStack pila=new NodeStack(1);
pila.push(1);
pila.print();
pila.push(2);
pila.print();
pila.push(3);
pila.print();
pila.push(4);
pila.print();
pila.push(5);
pila.print();
pila.push(6);
pila.print();
pila.peek();
pila.print();
pila.peek();
pila.print();
pila.peek();
pila.print();
pila.peek();
pila.print();
pila.peek();
pila.print();
System.out.println(pila.pop());
}
}
Lo Que imprime en pantalla:
No hay comentarios:
Publicar un comentario