Uebungsaufgaben/Semester2/Vorlesung2.java
2024-05-18 22:35:28 +02:00

72 lines
1.7 KiB
Java

package Semester2;
import java.util.Stack;
public class Vorlesung2 {
private int value;
private Vorlesung2 nextElement;
private Vorlesung2 previousElement;
public Vorlesung2(int value, Vorlesung2 nextElement, Vorlesung2 previousElement) {
this.value = value;
this.nextElement = nextElement;
this.previousElement = previousElement;
}
public static void main(String[] args) {
Vorlesung2 stack = new Vorlesung2(0, null, null);
stack.push(7);
stack.push(3);
stack.push(8);
stack.push(2);
System.out.println(stack.pop());
System.out.println(stack.pop());
stack.push(7);
System.out.println(stack.pop());
System.out.println(stack.pop());
}
public void push(int i) {
if (this.nextElement != null) {
this.nextElement.push(i);
} else {
this.nextElement = new Vorlesung2(i, null, this);
}
}
public int pop() {
if (this.nextElement != null) {
return nextElement.pop();
} else {
if (this.previousElement != null) {
this.previousElement.nextElement = null;
} else {
System.out.println("Stack is empty");
return 0;
}
return this.value;
}
}
}
class withJavasPackage {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(7);
stack.push(3);
stack.push(8);
stack.push(2);
System.out.println(stack.pop());
System.out.println(stack.pop());
stack.push(7);
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}