implementacja stosu (bez kolekcji)
8 04 2008import java.util.*;
public class stos<T> {
public stos() {
top=null;
}
private class Node<U> {
U item;
Node<U> next;
Node() {item= null; next= null; }
Node(U item, Node<U> next) {
this.item=item;
this.next=next;
}
boolean end() { return item== null && next== null; }
}
private Node<T> top= new Node<T>();
public void push(T item) {
top= new Node<T>(item,top);
}
public T pop() {
T result= top.item;
if(!top.end()) {
top=top.next;
}
return result;
}
@Override
public String toString() {
String s=”";
if(top==null)
{
s=”Z pustego i Salomon nie naleje :P - Stos jest pusty !!”;
return s;
}
for(Node tmp=top; tmp!=null; tmp=tmp.next)
{
s=s+”(”+tmp.item+”)”;
}
return s;
}
public static void main(String args[])
{
stos<Integer> stos = new stos<Integer>();
stos.push(10);
stos.push(20);
System.out.println(stos);
stos.push(30);
stos.push(40);
System.out.println(stos);
stos.pop();
stos.pop();
System.out.println(stos);
stos<String> stos2 = new stos<String>();
stos2.push(”a”);
stos2.push(”b”);
System.out.println(stos2);
stos2.push(”c”);
stos2.push(”d”);
System.out.println(stos2);
stos2.pop();
stos2.pop();
System.out.println(stos2);
}
}