Skip to content

Instantly share code, notes, and snippets.

@jmlon
Created March 4, 2020 22:11
Show Gist options
  • Save jmlon/343f57ef66ac262b5c79e1580205a056 to your computer and use it in GitHub Desktop.
Save jmlon/343f57ef66ac262b5c79e1580205a056 to your computer and use it in GitHub Desktop.
Ejemplo borrado de ultimo elemento, inversion del orden de los elementos con lista simple.
package edu.upb.estalg.Estructuras;
import edu.princeton.cs.algs4.StdOut;
public class DemoEstructura<T> {
private class Nodo {
T item;
Nodo sig;
}
Nodo first;
public void add(T item) {
Nodo n = new Nodo();
n.item = item;
n.sig = first;
first = n;
}
public void invert() {
Nodo next = first;
Nodo prev = null;
while(next!=null) {
Nodo actual = next;
next = actual.sig;
StdOut.println(actual.item);
actual.sig = prev;
prev = actual;
}
first = prev;
}
public boolean deleteLast() {
if (first==null) return false;
Nodo prev = null;
Nodo actual = first;
while (actual.sig!=null) {
prev = actual;
actual=actual.sig;
}
if (prev!=null) prev.sig=null;
else first=null;
return true;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for(Nodo i=first; i!=null; i=i.sig) sb.append(i.item+", ");
return sb.toString();
}
public static void main(String[] args) {
DemoEstructura<Integer> est = new DemoEstructura<>();
est.add(1);
est.add(2);
est.add(3);
StdOut.println("Original: "+est);
est.invert();
StdOut.println("Invertida: "+est);
est.deleteLast();
StdOut.println("Borro ultimo: "+est);
est.deleteLast();
StdOut.println("Borro ultimo: "+est);
est.deleteLast();
StdOut.println("Borro ultimo: "+est);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment