// Lista.cpp
// Definição dos métodos da classe cLista    ( Lista de Alunos )
//      Implementação com a técnica da sentinela

// Aula de 3 de Janeiro de 2002

#include "Lista.h"


cLista::cLista()
{
	
	Sentinela  = new cElemLista();    // Cria o elemento de controle   
	Tail = Sentinela;
	NrElementos = 0;
}

cLista::~cLista()
{
	cElemLista *p, *pNext;

	for ( p=Sentinela; p ;  )
	{
		pNext = p->Proximo;
		delete p;
		p = pNext;
	}
}


int cLista::GetNrElementos()
{
	return NrElementos;
}


// Inserção no fim
bool cLista::Inserir( cAluno Al )
{
	cElemLista *pNovo;
	
	pNovo = new cElemLista();

	pNovo->Aluno  = Al;
	
	Tail->Proximo = pNovo;
	
	Tail = pNovo;
	
	NrElementos ++;
	return true;
}

// Remove o aluno com o Nr 'NrAl'
bool cLista::Remover(  int NrAl  )
{
	cElemLista *p, *pAnt;
	bool Encontrou;

	if ( NrElementos == 0 ) return false;  // Se a lista estiver vazia ...
	
	Encontrou = Procurar( NrAl, p,  pAnt );

	if ( !Encontrou ) return false;

	pAnt->Proximo = p->Proximo ;

	if ( p == Tail ) // Se o elemento a remover estiver no fim
		Tail = pAnt;

	delete p;

	NrElementos --;
	return true;
}


cAluno *cLista::Obter( int pos )    //  0<= pos <= NrElementos 
{
	if ( pos < 0 || pos > NrElementos ) return 0;

	int i;
	cElemLista *p;

	for ( i=1, p=Sentinela->Proximo ; i < pos; i++, p=p->Proximo ) ;

	return &(p->Aluno) ;
}


bool cLista::Procurar( int NrAl,  cElemLista* &pEl ,cElemLista* &pAnterior )
{
	cElemLista *p, *pAnt;

	pAnt = Sentinela;
	p = Sentinela->Proximo ;

	while ( p && ( NrAl != p->Aluno.GetNr() ) )
	{
		pAnt = p;
		p = p->Proximo ;
	}

	pAnterior = pAnt;
	pEl = p;
	
	return ( p != 0 );
}
