Created
October 30, 2012 04:35
-
-
Save orlybg/3978318 to your computer and use it in GitHub Desktop.
Empiric single linked list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node | |
{ | |
private Node next; | |
private Object data; | |
public Node(Object data, Node next) { | |
this.next = next; | |
this.data = data; | |
} | |
public Node(Object data) { | |
this.data = data; | |
this.next = null; | |
} | |
public void setNext(Node next) { | |
this.next = next; | |
} | |
public Node whatsNext() { | |
return this.next; | |
} | |
public Object getData() { | |
return this.data; | |
} | |
} | |
public class SingleLinkedList | |
{ | |
private Node first; | |
private Node last; | |
private int size; | |
public SingleLinkedList() { | |
this.first = null; | |
this.last = null; | |
this.size = 0; | |
} | |
public static void main(String args[]) { | |
System.out.println("A ver que traes..."); | |
SingleLinkedList miLista = new SingleLinkedList(); | |
System.out.println(miLista.isEmpty()); | |
miLista.addLast(1); | |
miLista.addLast(2); | |
miLista.addLast(3); | |
miLista.traverse(); | |
miLista.delFront(); | |
System.out.println("first: " + miLista.getFirst().getData()); | |
System.out.println("last: " + miLista.getLast().getData()); | |
System.out.println(miLista.isEmpty()); | |
} | |
public boolean isEmpty() { | |
return (this.first == null); | |
} | |
public Node getFirst() { | |
return this.first; | |
} | |
public Node getLast() { | |
return this.last; | |
} | |
public void addFront(Object data) { | |
Node node = new Node(data); | |
if (this.first == null) { | |
node.setNext(null); | |
this.last = node; | |
} else { | |
node.setNext(this.first); | |
} | |
this.first = node; | |
this.size += 1; | |
} | |
public void addLast(Object data) { | |
Node node = new Node(data); | |
if (this.first == null) { | |
node.setNext(null); | |
this.first = node; | |
} else { | |
this.last.setNext(node); | |
} | |
this.last = node; | |
} | |
public void delFront() { | |
if (this.first != null) { | |
Node toDel = first; | |
Node newFirst = toDel.whatsNext(); | |
toDel = null; | |
this.first = newFirst; | |
this.size -= 1; | |
} | |
} | |
/*public int search(Object needle) { | |
}*/ | |
public void traverse() { | |
Node current = first; | |
while (current != null) { | |
System.out.println(current.getData()); | |
current = current.whatsNext(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment