Ir para conteúdo
Fórum Script Brasil
  • 0

Tabela Hash + Lista Encadeada (AJUDA)


Yannick Freitas

Pergunta

Então Galera, preciso fazer o método procura, que esta no arquivo TLista.cpp, o método procura tem que pesquisar dentro da Lista pelo nome. E retornar a posição dentro da tabela hash. Postei todos os arquivos que utilizo no código. Obrigado!

header

#include <iostream>
#include <string>
#include <stdlib.h>
#include <errno.h>
#include <fstream>
#include <sstream>
#include <time.h>
#include <stdio.h>
#include <sys/time.h>
#include <cmath>

using namespace std;

#define PRINT(arg)  #arg "=" << arg << ", "
#define PRINTN(arg)  #arg "=" << arg << endl

#define CINE(arg)  { cin >> arg; if (!cin) { cerr << "CINE failed reading var >" #arg "< in file >" __FILE__ "< at line >" << __LINE__ << "<."  << endl; exit(2);}}

#define CINE3(a,b,c) CINE(a);CINE(b);CINE(c)
#define CINE4(a,b,c,d) CINE(a);CINE(b);CINE(c);CINE(d)

#define CINE8(a,b,c,d,e,f,g,h) CINE(a);CINE(b);CINE(c);CINE(d);CINE(e);CINE(f);CINE(g);CINE(h)


#define GETLINE(string)  { getline(cin,string); if (!cin) { cerr << "GETLINE failed reading string " #string  << " in file " __FILE__ " at line " << __LINE__  << endl; exit(1);}}


//#define NEWA(var,type,size) {  e=1; }

//#define NEWA(var,type,size) { if(0==(var=new type [(size)])) e=1; }

#define NEWA(var,type,size) { try  { if(0==(var=new type [(size)])) throw;} catch (...)  { cerr << "NEWA failed on " #var "=new " #type "[" #size "=" << (size) << "]" << endl; exit(1); }}
main.cpp
#include <cstdlib>
#include <iostream>
#include "TLista.h"
#include "THash.h"

using namespace std;

int main(int argc, char *argv[])
{   
    THash h1(5);
    
    TPessoa a1;
    
    char op;
    do{
       cout << "\n \n \n \t \t******** MENU OPERACOES ********* \n";
       cout << "\t\t 1 - Informar o tamanho da tabela HASH \n";
       cout << "\t\t 2 - Inserir elemento \n";
       cout << "\t\t 3 - Imprimir tabela hash\n";
       cout << "\t\t S - Sair\n";
       cout << "\t \t********************************* \n";
       cout << "\t\t Digite sua opcao:";
       cin >> op;
       
       system("cls");
       
       if(op == '1'){
             cout << "\n-----DEFININDO O TAMANHO DA TABELA ----\n";
             int t;
             cout<<"Novo tamanho:";
             cin >> t; 
             h1.setTamanho(t);
             cout << "\n----------------------------------------\n";
       }else if(op == '2'){
             cout << "\n-----INSERCAO DE CADASTRO------\n";
             cout<< "Nome:";
             cin >> a1.nome;
             cout<< "Rg:";
             cin >> a1.rg;
             cout<< "Idade:";
             cin >> a1.idade;
             cout<< "Salario:";
             cin >> a1.salario;             
             h1.insere(a1);             
             cout << "\n-----------------------------\n";
       }else if(op=='3'){
            h1.imprime();
       }
    }while(op != 's');
    
    system("PAUSE");
    return EXIT_SUCCESS;
}
THash.cpp
#include "THash.h"
#include <iostream>
using std::ostream;


THash::THash ()  {   // construtor 
    tam = 0;
    alfabeto = "abcdefghijklmnopqrstuvwyz";
}

THash::THash (int t)  {   // construtor 
     tam = t;
     tabelaHash = new TLista[tam];
     alfabeto = "abcdefghijklmnopqrstuvwyz";
}

void THash::setTamanho(int t){
   tam = t;
   delete tabelaHash;
   tabelaHash = new TLista[tam];
}

bool THash::insere(TPessoa a){
int i;
i = funcaoHash(a);
tabelaHash[i].insere(a);

}

int THash::getPosicao(char letra){

}


int THash::funcaoHash(TPessoa a){
    string nome = a.nome;    
    double somatorio = 0;
    int indice;
    int posicaoDaLetra;


    int i=0;
    char l = nome[i];
    while(l != ''){
      posicaoDaLetra = getPosicao(l);
      if(posicaoDaLetra >= 0)
         somatorio = somatorio + getPosicao(nome[i]);
      else
         cerr << "Erro - Letra não encontrada.";                   
      i++;
      l = nome[i];            
    }
    
    indice =  (int) somatorio;
    indice = indice % tam;
    cout << "Pos:"<<indice;
    return indice;
}

void THash::imprime(){
    cout<<"\n********************  TABELA HASH ********************* \n";
    for(int i=0; i<tam; i++){
       tabelaHash[i].imprime(i);
    }
    cout<<"******************************************************* \n";

}
THash.h
#ifndef _THash_H__
#define _THash_H__

#include "header"
#include "TNodo.h"
#include "TLista.h"

using std::ostream;

//typedef basic_string<char> string;

class THash { 
   public:
     THash();
     THash(int t);
     void setTamanho(int t);
     bool insere(TPessoa a);
     void imprime();

   private:
     int getPosicao(char letra);
     int funcaoHash(TPessoa a);
     
     string alfabeto; 
     int tam;
     TLista * tabelaHash;
};


#endif
TLista.cpp
#include <assert.h>
#include <iostream>
using std::ostream;
using std::cout;

#include "TLista.h"

////////////////////////
// Funções públicas
////////////////////////

TLista::TLista() {
    tam = 0;
    head = NULL;
}
  
TNodoPtr TLista::n_esimo(int n) const {  
         TNodoPtr p=head;
         int j=1;
         while((j<n)&&(p->prox!=NULL)){
                p=p->prox;
                j++;
         }
          return p;
}

int TLista::posicao(TNodoPtr p) const {  
    assert(p);       // assegura referencia valida
    TNodoPtr tmp;
    int i=1;
   
    tmp=head; 
    while (tmp && tmp != p) { 
       tmp = tmp->prox;
       i++;
    }
    
    if (tmp == p)
        return i;
    else
        return 0;
}
TNodoPtr TLista::procura(TPessoa a) const {  
                                        
}

bool TLista::insere(TPessoa a) {  
     TNodoPtr novo = new TNodo(a,NULL); 
                   novo -> prox = head;
                   head = novo;                   
                   tam ++;  

}

bool TLista::remove(TNodoPtr p) {  
    assert(p); // testa posicao de remocao valida

    TNodoPtr tmp;
    if (p == head) {  // remove o primeiro TNodo
       tmp = head;
       head = head->prox;
       delete(tmp);
       return true;
    } else {  
       tmp = head;
       while (tmp->prox != p)
         tmp = tmp->prox;
       tmp->prox = p->prox;
       delete(p);
       return true;
    }
}  

unsigned int TLista::tamanho() const {  
    int count=0;
    for (TNodoPtr p=head; p; p=p->prox)
       count++;
    return(count);
}

void TLista::imprime(int i) const {  
     cout<<endl<< "------------------------------------------------------"<<endl;
     cout << "Indice "<< i <<" tem "<< tam <<" elementos"<< endl;
     int j;
     
     TNodoPtr p = head;
     if(!p)
        cout << "";//cout << "Lista vazia.";
     else{
        int i=0;
        while(p){
          cout << "("<< p->item.nome <<","<< p->item.rg <<","<< p->item.idade <<","<< p->item.salario<<") ";
          p = p->prox;
          i++;
        }
     }
     cout<< endl <<"------------------------------------------------------"<<endl;
}

bool TLista::EstaVazia() const { 
   return (head == NULL);
}

TLista::~TLista() {  

}
TLista.h
#ifndef _TLista_H__
#define _TLista_H__

#include "TNodo.h"
#include <iostream>

using std::ostream;

class TLista { 
   public:
     TLista();                            // construtor de TLista vazia
     TNodoPtr n_esimo(int n) const;       // retorna uma referencia para o n-esimo item
     int posicao(TNodoPtr p) const;       // retorna a posicao do item referenciado por p
     
     TNodoPtr procura(TPessoa p) const;   // retorna uma referência para o nodo tal que item == it
     bool insere(TPessoa a);              // insere o item it na primeira posicao 
     bool remove(TNodoPtr p);             // remove o item referenciado por p

     unsigned int tamanho() const;        // número de nodos na TLista
     void imprime(int i) const;           // imprime os itens da TLista
     
     bool EstaVazia() const;              // retorna verdadeiro se a TLista esta vazia
     ~TLista();                           // destrutor de TLista

   private:
     TNodoPtr head;        // apontador para o primeiro nodo  da TLista 
     int tam;
};   

#endif
TNodo.cpp
TNodo::TNodo (TPessoa a, TNodoPtr ptr=NULL)  {   // construtor 
        item = a;
        prox = ptr;
}
TNodo.h
#ifndef _TNodo_H__
#define _TNodo_H__

#include <iostream>
#include <sstream>
#include <string>

#include "header"

using std::ostream;

//typedef basic_string<char> string;

struct TPessoa{
       string nome;
       string rg;
       int idade;
       double salario;
};

class TNodo;

typedef TNodo* TNodoPtr;      // apontador para um nodo da lista

class TNodo { 
   friend class TLista;
   friend class THash;

   public:
     TNodo (TPessoa a, TNodoPtr ptr);

   private:
     TPessoa item;
     TNodoPtr  prox;
};


#endif

Link para o comentário
Compartilhar em outros sites

0 respostass a esta questão

Posts Recomendados

Até agora não há respostas para essa pergunta

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...