Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Cambiar head por tail e usar "https://pastebin.com/F8Dbake1".
- public class Pila<T> {
- private NodoPila<Object> head;
- private NodoPila<Object> tail;
- int count;
- public Pila() {
- head=null;
- count=0;
- tail=null;
- }
- //saber pila vacia.
- public boolean empty() {
- return head==null;
- }
- //pushear un elemento a la Pila.
- public void push(Object element) {
- NodoPila<Object> temp = new NodoPila<Object>(element);
- if(count==0) {
- this.head=this.tail=temp;
- ++count;
- }else {
- this.tail.next=temp;
- this.tail=temp;
- ++count;
- }
- }
- //pop un elemento de la Pila.
- public Object pop() {
- if (empty()) {
- throw new RuntimeException("La pila está vacía...");
- }
- Object item = this.tail.data;
- if (this.head.next == null) {
- this.head = this.tail = null;
- } else {
- NodoPila<Object> skip = this.head;
- while (skip.next.next != null) {
- skip = skip.next;
- }
- this.tail = skip;
- this.tail.next = null;
- }
- --this.count;
- return item;
- }
- //peek muestra sin sacar cima de Pila.
- public Object peek() {
- if (empty()) {
- throw new RuntimeException("La pila está vacía...");
- }
- return tail.data;
- }
- //tamaño Pila.
- public int size() {
- return count;
- }
- //region Object Methods
- @Override
- public String toString() {
- if (size() <=0) {
- return "La pila se encuentra Vacia....desu";
- }
- // from https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/StringBuilder.html
- StringBuilder sb = new StringBuilder();
- //Crear tail enlazarlo con el primer modo cargado y utilizarlo para recorre la pila correctamente.
- sb.append("[" + head.data.toString());
- for (NodoPila<?> skip = head.next; skip != null; skip = skip.next) {
- sb.append(", " + skip.data.toString());
- }
- sb.append("]");
- return sb.toString();
- }
- //endregion
- }
Add Comment
Please, Sign In to add comment