Informatikks1/Stack.java

106 lines
2.1 KiB
Java

public class Stack
{ private Node<T> first;
public List() {
first = null;
}
public boolean isEmpty() {
if (first == null) return true;
return false;
}
public int size() {
Node<T> current = first;
int count = 0;
while (current != null) {
count++;
current = current.next;
}
return count;
}
public T get(int n) {
Node<T> current = first;
for (int i = 0; i < n; i++) {
if (current == null) return null;
current = current.next;
}
if (current == null) return null;
return current.wert;
}
public void add(T val) {
Node<T> neu = new Node<T>();
neu.wert = val;
if (first == null) {
first = neu;
} else {
Node<T> current = first;
while (current.next != null) {
current = current.next;
}
current.next = neu;
}
}
public void add(int n, T val) {
if (n >=size()) {
add(val);
return;
}
Node<T> neu = new Node<T>();
neu.wert = val;
if (n==0){
neu.next = first;
first = neu;
return;
}
Node<T> current = first;
for (int i = 0; i < n-1; i++){
current = current.next;
}
neu.next = current.next;
current.next = neu;
}
public boolean contains(T val) {
Node<T> current = first;
while (current != null) {
if (current.wert.equals(val)) return true;
}
return false;
}
public T pull(int n) {
T tmp = first.wert;
first = first.next;
return tmp;
}
public String toString(){
String result = "";
Node<T> current = first;
while (current != null) {
result += current.wert + ", ";
current = current.next;
}
return result;
}
}