package lista;

public class KruznaLista extends VezanaLista {
/*    public synchronized Cvor getTail() {
	Cvor p,q;

	for (p=pocetak;(q=p.getNext())!=pocetak;p=q);

	return p;
    }*/
    private Cvor pocetak=null;
    private Cvor tail=null;

    public synchronized Cvor getTail() {
	return tail;
    }

    public synchronized void insertAtHead(Cvor cvor) {
	if (pocetak==null || tail==null) {
	    cvor.setNext(cvor);
	    pocetak=cvor;
	    tail=cvor;
	}
	else {
	    cvor.setNext(pocetak);
	    tail.setNext(cvor);
	    pocetak=cvor;
	}
    }

    public synchronized void insertAtTail(Cvor cvor) {
	if (pocetak==null || tail==null) {
	    cvor.setNext(cvor);
	    pocetak=cvor;
	    tail=cvor;
	}
	else {
	    cvor.setNext(pocetak);
	    tail.setNext(cvor);
	    tail=cvor;
	}
    }

    public synchronized Cvor removeFromHead() {
	Cvor cvor=pocetak;
	
	if (pocetak!=null) {
	    if (pocetak==pocetak.getNext()) {
		pocetak=null;
		tail=null;
	    }
	    else {
		tail.setNext(pocetak.getNext());
		pocetak=pocetak.getNext();
	    }
	}
	return cvor;
    }

    public synchronized Cvor removeFromTail() {
	Cvor cvor=pocetak;

	if (pocetak==null) return null;

	if (pocetak==pocetak.getNext()) {
	    pocetak=null;
	    tail=null;
	    return cvor;
	}

	Cvor p;

	for (p=pocetak;p.getNext()!=tail;p=p.getNext());

	// U ovom trenutku je tail sljedeci nakon p 
	
	cvor=p.getNext();
	p.setNext(pocetak);
	tail=p;

	return cvor;
    }

    public synchronized void remove(Cvor cvor) {
	if (pocetak==null) return;

	if (pocetak==pocetak.getNext()) {
	    if (cvor.equals(pocetak)) {
		pocetak=null;
		tail=null;
	    }
	}
	else {
	    if (cvor.equals(pocetak)) {
		tail.setNext(pocetak.getNext());
		pocetak=pocetak.getNext();
	    }
	    else {
		Cvor p,q;
		for (p=pocetak;(q=p.getNext())!=pocetak;p=q) {
		    if (cvor.equals(q)) {
			if (tail==q) tail=p;
			p.setNext(q.getNext());
			return;
		    }
		}
	    }
	}
    }
}
