mirror of
https://gitlab.com/harald.mueller/aktuelle.kurse.git
synced 2024-11-30 21:51:56 +01:00
113 lines
1.5 KiB
Java
113 lines
1.5 KiB
Java
|
|
public class MyStack {
|
|
|
|
|
|
private Node first;
|
|
private int elements;
|
|
|
|
|
|
public MyStack(){
|
|
//first = new Node(null); //don't add empty element!
|
|
elements = 0;
|
|
}
|
|
|
|
|
|
/**
|
|
* Adds element to the list (head of list)
|
|
* @param element
|
|
*/
|
|
public void push(Object element){
|
|
|
|
//the new element is the last in the list:
|
|
Node old = first;
|
|
first = new Node(element);
|
|
first.setNext(old);
|
|
elements++;
|
|
}
|
|
|
|
/**
|
|
* Removes element from head of list
|
|
* @return
|
|
*/
|
|
public Object pop(){
|
|
Object element = first.getItem();
|
|
first = first.next;
|
|
elements--;
|
|
|
|
return element;
|
|
}
|
|
|
|
|
|
public void showElements(){
|
|
|
|
Node current = first;
|
|
while (current != null){
|
|
System.out.println("Elements = " + current.getItem().toString());
|
|
current = current.getNext();
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
//Inner class with the data structure of the linked list
|
|
private class Node{
|
|
|
|
//these are private
|
|
Object item;
|
|
Node next;
|
|
|
|
//constructor
|
|
public Node (Object value){
|
|
next = null;
|
|
item = value;
|
|
}
|
|
|
|
//standard getter and setter methods
|
|
|
|
public Object getItem() {
|
|
return item;
|
|
}
|
|
|
|
|
|
public void setItem(Object item) {
|
|
this.item = item;
|
|
}
|
|
|
|
|
|
public Node getNext() {
|
|
return next;
|
|
}
|
|
|
|
|
|
public void setNext(Node next) {
|
|
this.next = next;
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
//TESTS:
|
|
|
|
public static void main(String[] args) {
|
|
|
|
MyStack stack = new MyStack();
|
|
stack.push("to");
|
|
stack.push("be");
|
|
stack.push("or");
|
|
stack.showElements();
|
|
System.out.println("pop....");
|
|
stack.pop();
|
|
stack.showElements();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|