package hr.fer.oop.part1.MI2016.treci;
public class Stog<T> {
private ElementStoga<T> peak, glava;
private int count;
public Stog(){
glava = null;
peak = null;
count = 0;
}
/**
* Stavlja element na vrh stoga.
* @param element novi element
* @return true ako je uspješno dodan, false inače
*/
public boolean push(T element) {
if(element == null)
throw new IllegalArgumentException();
ElementStoga<T> novi = new ElementStoga<>(element, null);
peak = novi; // vrh stoga sada pokaziva na novi element
if (glava == null || peak == null) {
glava = novi;
} else {
ElementStoga<T> temp = glava; // ok
while (temp.next != null) {
temp = temp.next;
}
temp.next = novi;
}
this.count++;
return true;
}
/**
* Skida element s vrha stoga
* @return element na koji pokaziva vrh stoga
*/
public T pop() {
if(this.isEmpty()==true) {
System.err.println("Stog je prazan");
}
T povratna = peak.value;
ElementStoga<T> glavaPom = glava;
while(glavaPom.next.next != null){
glavaPom = glavaPom.next;
}
peak = glavaPom;
glavaPom.next = null; // brisanje sa kraja liste
this.count--;
return povratna;
}
/**
*
* @return broj elemenata na stogu
*/
public int size() {
return this.count;
}
/**
* Provjerava je li stog prazan
* @return true ako je prazan, false inače
*/
public boolean isEmpty() {
return (this.count==0);
}
public void forEach(Obrada<T> operator) {
while(this.count != 0) {
operator.obradi(this.pop());
}
}
}
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.