Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package tabela;
- public class TabelaHash {
- class Elo {
- private int valor;
- private Elo prox = null;
- public Elo(int valor) {
- this.valor = valor;
- }
- }
- private Elo[] elos;
- private int quantidade;
- public TabelaHash(int quantidade) {
- this.quantidade = quantidade;
- this.elos = new Elo[quantidade];
- }
- private int hash(int valor) {
- return valor % quantidade;
- }
- private Elo percorrer(Elo elo,int valor) {
- if( elo.valor == valor || elo.prox == null) {
- return elo;
- }
- return percorrer(elo.prox,valor);
- }
- private void percorrerDel(Elo elo,int valor){
- if(elo.prox == null) {
- System.out.println("Elemento não encontrado");
- return;
- }
- if(elo.prox.valor == valor) {
- System.out.println("Elemento removido com sucesso");
- elo.prox = elo.prox.prox;
- return;
- }
- percorrerDel(elo.prox,valor);
- return;
- }
- public boolean buscar(int valor) {
- int posicao = this.hash(valor);
- if(this.elos[posicao] == null) {
- return false;
- }
- if(this.elos[posicao].valor == valor) {
- return true;
- }
- Elo elo = percorrer(this.elos[posicao].prox,valor);
- if(elo.valor == valor) {
- return true;
- }
- return false;
- }
- public boolean insere(int valor) {
- int posicao = this.hash(valor);
- if(this.elos[posicao] == null) {
- this.elos[posicao] = new Elo(valor);
- return true;
- }
- if(this.elos[posicao].valor == valor) {
- System.out.println("Valor já existe na tabela");
- return false;
- }
- Elo elo = percorrer(this.elos[posicao],valor);
- if(elo.valor == valor) {
- System.out.println("Valor já existe na tabela");
- return false;
- }else {
- elo.prox = new Elo(valor);
- return true;
- }
- }
- public void remove(int valor) {
- int posicao = this.hash(valor);
- if(this.elos[posicao] == null) {
- System.out.println("Valor não existe na tabela");
- return;
- }
- if(this.elos[posicao].valor == valor) {
- System.out.println("Elemento removido com sucesso");
- this.elos[posicao] = this.elos[posicao].prox;
- return;
- }
- this.percorrerDel(this.elos[posicao], valor);
- }
- public static void main(String[] args) {
- TabelaHash tabela = new TabelaHash(3);
- for(int i=0;i<10;i++) {
- tabela.insere(i);
- }
- for(int i=0;i<10;i++) {
- int valor = (int) (Math.random() * 11);
- tabela.remove(valor);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement