package sub.datastructure;
public class Stack {
private Node head;
private Node tail;
private int length;
public Stack() {
head = new Node();
tail = head;
length = 0;
}
public void push(Object data) {
Node node = new Node(data);
node.setNext(head);
head = node;
length++;
}
public Node pop() {
if(length == 0) return null;
Node node = head;
head = node.getNext();
node.getNext().setNext(null);
length--;
System.gc();
return node;
}
public void print() {
Node node = head;
while(node.getNext() != null) {
System.out.println(node.getData());
node = node.getNext();
}
}
}
Sabtu, 21 Februari 2009
Stack Using Java
Create Node
package sub.datastructure;
public class Node {
private Object data;
private Node next;
public Node() {
}
public Node(Object data) {
this.data = data;
}
public void setData(Object data) {
this.data = data;
}
public void setNext(Node next) {
this.next = next;
}
public Object getData() {
return data;
}
public Node getNext() {
return next;
}
}
Langganan:
Postingan (Atom)