Implement and perform joint operations on chain lists

Asked

Viewed 1,949 times

4

Could someone help me implement a chained list to perform set operations? Without using native Java functions such as ArrayList.

The algorithm already generates a chained list and adds new nodes, but how do I make an operation like the union?

In the Main, I am instantiating two classes, each one would be a list with values, but what do I call a union function that takes as a parameter these two lists and how to go through them simultaneously? (I know how to go one at a time)

Code - Main

public class TrabalhoListas {

public static void main(String[] args) {
    ListaDinamica teste = new ListaDinamica();
    ListaDinamica teste2 = new ListaDinamica();
    teste.add(1);
    teste.add(2);
    teste.add(3);
    teste.imprimeLista();
    System.out.println("Segunda lista");
    teste2.add(1);
    teste2.add(6);
    teste2.add(3);
    teste2.imprimeLista();
    System.out.println("Primeira de novo");
    teste.imprimeLista();
}
}

--- List ---

public class Lista {

private int valor;
private Lista prox;

public Lista() {
}

public int getValor() {
    return valor;
}

public void setValor(int valor) {
    this.valor = valor;
}

public Lista getProx() {
    return prox;
}

public void setProx(Lista prox) {
    this.prox = prox;
}
}

Lista Dinâmica

public class ListaDinamica {

Lista primeiro;
Lista ultimo;
int tamanho = 0;

public ListaDinamica() {
    primeiro = null;
    ultimo = primeiro;
}

public void add(int valor) {
    Lista novo = new Lista();
    novo.setValor(valor);
    tamanho++;
    if (primeiro == null) {
        primeiro = novo;
        ultimo = novo;
        novo.setProx(null);
    } else {
        novo.setProx(primeiro);
        primeiro = novo;
    }
}

public void imprimeLista() {
    Lista atual = primeiro;
    for(int i = 0; i < tamanho; i++){
        System.out.println(atual.getValor());
        atual = atual.getProx();
    }
}

public void uniao(){

}
}
  • Post the code of what you tried, even if it’s wrong or incomplete.

  • Okay, I’ll be putting Main and the file I’m adding.

3 answers

0

To make the union between two lists, just go through the list 1 until the last "valid element"( !=null) and add to list 2 as next to this element.

public static void uniaoLista(Lista l1, Lista l2){

    //Lista auxiliar que vai percorrer a lista 1
    Lista lAux = l1;


    //Percorre a lista l1 até chegar ao ultimo "elemento válido", ou seja, != de null
    while(lAux.getProx()!=null){

        lAux = lAux.getProx();
    }

    //Quando este elemento é achado, dizemos que seu próximo elemento será a lista l2
    lAux.prox = l2;
}

Thus, you would not need to create a class "Dynamic List", it would be enough to have a List object that receives the first list and then make the union between this list and another one. Example:

Suppose the lists:

List L1 = 1->2->3->4

List L2 = 5->6->7->8

To perform the union without ending the list L1, once the objects are passed by reference, do:

...
Lista lUniao = l1.clone();
uniaoLista(lUniao,l2);

//lUniao = 1->2->3->4->5->6->7->8
  • Right, but how do I pass the lists as parameter? On Main, my lists would be test and test2, as I would send to the uniaoList method? And I also need to do a check, for example, if L1 = 1->2->3 and L2 = 2->3->4, only 4 will be inserted in the new list, the values will not repeat between sets.

  • I think the problem you are having is that the uniaoList() method is within a class, so Oce would need to test 1.uniaoList() or teste2.uniaoList(). Do the following, put the list union method on Main, not forgetting to put the method as static

  • Right putting in Main, da para passar por paramêtro, but another problem arises, as I need to verify equalities, I need to go through the list, and my global variables, as first and last are in the Listdinamica class, and to add values in the list is also performed in the list.

0


I think that would be it, that simply modifies a ListaDinamica concatenating in her another ListaDinamica:

public void uniao(ListaDinamica outraLista) {
    ultimo.setProx(outraLista.primeiro);
    ultimo = outraLista.ultimo;
    tamanho += outraLista.tamanho;
    removeDuplicatas();
}

And to remove duplicates, you end up going through the same list twice, one inside the other:

private void removeDuplicatas() {
    for (Lista a = primeiro; a != null; a = a.getProx()) {
        for (Lista b = a.getProx(); b != null; b = b.getProx()) {
            if (a.getValor() == b.getValor()) {
                a.setProx(b.getProx());
                tamanho--;
            }
        }
    }
}

This algorithm to remove duplicates is not very efficient (it has quadratic time complexity), but it should work properly and should serve its purposes. Figuring out an efficient algorithm for this would be much more complicated, and in this case it would be better to use the classes that java already gives you (such as HashSet or TreeSet).

You should also place a call to removeDuplicatas() at the end of the method add(int). Or create a search method and use it in the method add(int) to avoid adding an existing element.

And then, you use this method at the end of the method main:

teste.uniao(teste2);
teste.imprimeLista();

If you prefer to join without modifying either list, then the best approach is to follow the of my other answer.

  • But in this case it would concatenate everything, however a union of sets, only aggregates values that do not exist in one set but contain in the other. That is, he cannot repeat the values.

  • @Natalia I edited my answer to remove duplicates.

  • now I was in doubt, about mathematics even, case A[1, 2, 1] and B[3, 4, 5] the union would not be C[1, 2, 1, 3, 4, 5]? Or the numbers of a set cannot be repeated within it?

  • @Natalia Sets, as defined in mathematics, have no repeating elements and no well-defined order of the elements. Example: let A be the set of countries of Europe and B the set of countries that start with the letter E. In the set that is the union of A and B we have Spain, but we do not have two Spains. There is also nothing saying whether Spain comes before Slovenia or not (unless we come to define some sort of ordination criterion). The same applies to the intersection.

  • I understood and in what place I invoke this method of union, and as I pass to them the values of List A and B?

  • @Natalia Resposta editada.

Show 1 more comment

0

You can add a method to find out if an element exists in ListaDinamica:

public boolean existe(int elemento) {
    for (Lista a = primeiro; a != null; a = a.getProx()) {
        if (a.getValor() == elemento) return true;
    }
    return false;
}

Modify the method add(int) not to add duplicates:

public void add(int valor) {
    if (existe(valor)) return; // Não deixa adicionar duplicatas.
    Lista novo = new Lista();
    novo.setValor(valor);
    tamanho++;
    if (primeiro == null) {
        primeiro = novo;
        ultimo = novo;
        novo.setProx(null);
    } else {
        novo.setProx(primeiro);
        primeiro = novo;
    }
}

And in the union, just add all the elements of the other list:

public void uniao(ListaDinamica outraLista) {
    for (Lista a = outraLista.primeiro; a != null; a = a.getProx()) {
        add(a.getValor());
    }
}

And then, you use this method at the end of the method main:

teste.uniao(teste2);
teste.imprimeLista();

Maybe you don’t like the fact of the method uniao modify the list. If this is the case, and you actually want to create a new list without modifying either one, then do this:

public ListaDinamica uniao(ListaDinamica outraLista) {
    ListaDinamica novaLista = new ListaDinamica();
    for (Lista a = primeiro; a != null; a = a.getProx()) {
        novaLista.add(a.getValor());
    }
    for (Lista a = outraLista.primeiro; a != null; a = a.getProx()) {
        novaLista.add(a.getValor());
    }
    return novaLista;
}

And then in your method main:

ListaDinamica teste3 = teste.uniao(teste2);
teste3.imprimeLista();
  • Right and where I invoke this method, and how I pass the values of the added lists?

  • @Natalia Resposta editada.

  • It does not allow to assign test.union, reports as incompatibility, you would have another type of contact with the Hangout or something of the genre? I need to understand how to go through these two lists simultaneously to do some checking, and try to solve my union problem. Of course, if I don’t have that chance I’ll understand.

  • @Natalia The first method uniao that I gave is void. He modifies the list teste instead of creating a new list. The second method uniao that I gave uses the approach of creating a new list. The two approaches are mutually incompatible with each other and you will probably just want to choose one of them. The way you will put them on main depends on the approach you choose.

  • @Natalia As for contact me, you can pick up my email on my user page (just click on the link with my name and "scroll" the frame right to the end). But here at Stackoverflow, there’s a lot of people who can help you, and I’m just one.

  • is that you were very clear about your answer, I managed to accomplish, however I need only understand a question, I will contact you, if you are available clear.

  • @Natalia Ok. :)

  • I just emailed you, and I thank you for your help and for the patience of both you and everyone who’s paid attention.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.