Concatenation of two chained lists

Asked

Viewed 1,263 times

4

The problem is:

Write a program and make a function to concatenate two lists of integers into a third list that must be returned by the function, in C#.

My doubt is only on how to concatenate the list.

Code of the class representing the list (Lista)

using System;

namespace ListaLib
{
    public class Lista
    {
        /// <summary>
        /// Referência do primeiro nó (elemento) da lista
        /// </summary>
        public NoLista InicioLista { get; set; }

        /// <summary>
        /// Construtora da classe lista
        /// </summary>
        public Lista()
        {
            InicioLista = null;
        }

        /// <summary>
        /// Remove um valor da lista
        /// </summary>
        /// <param name="valor">Valor a ser removido</param>
        /// <returns>true se encontrar e false se não encontrar</returns>
        public bool Remove(int valor)
        {
            bool valorRetorno = false;

            NoLista auxiliar = InicioLista;

            // Verificar se a lista está vazia
            if (auxiliar != null)
            {
                // Percorrer  lista (navegar) até achar o nó com o valor desejado
                while ((auxiliar != null) && (auxiliar.informacao != valor))
                {
                    // Passa para o próximo elemento da lista
                    auxiliar = auxiliar.proximo;
                }

                // So atualizar a lista se o valor foi encontrado
                if (auxiliar.informacao == valor)
                {
                    // Verificar se existe um proximo elemento na lista
                    if (auxiliar.proximo != null)
                    {
                        // Remover a referencia do nó anterior
                        (auxiliar.proximo).anterior = null;
                    }

                    // Verificar se é o primeiro da lista
                    if (InicioLista.informacao == valor)
                    {
                        InicioLista = InicioLista.proximo;
                    }
                    else
                    {
                        // Verificar se existe um proximo elemento na lista
                        if (auxiliar.proximo != null)
                        {
                            (auxiliar.proximo).anterior = auxiliar.anterior;
                        }

                        // Fazer o anterior do auxiliar apontar para o proximo do auxiliar
                        (auxiliar.anterior).proximo = auxiliar.proximo;
                    }
                }
            }

            return valorRetorno;
        }

        /// <summary>
        /// Adiona um novo valor na lista
        /// </summary>
        /// <param name="valor">Valor a ser adicionado</param>

        public void Add(int valor)
        {
            NoLista novoNo = new NoLista();
            novoNo.informacao = valor;

            // Verificar se é o primeiro da lista
            if (InicioLista == null)
            {
                InicioLista = novoNo;
            }
            else
            {
                NoLista auxiliar = InicioLista;

                while (auxiliar.proximo != null)
                {
                    auxiliar = auxiliar.proximo;
                }

                auxiliar.proximo = novoNo;
                novoNo.anterior = auxiliar;
            }
        }


        }

        public void Imprime()
        {
            NoLista auxiliar = InicioLista;
            Console.WriteLine("Imprimindo a lista");

            // Percorrer a lista até o fim
            while (auxiliar != null)
            {
                // Imprimir o valor
                Console.WriteLine(auxiliar.informacao);

                // Navegar para o próximo nó
                 auxiliar = auxiliar.proximo;
            }
        }
    }

The class representing the nodes on this list (NoLista)

namespace ListaLib
{
    public class NoLista
    {
        /// <summary>
        /// Aramazena a informação
        /// </summary>
        public int informacao { get; set; }

        /// <summary>
        /// Referência para o próximo nó (elemento) na lista
        /// </summary>
        public NoLista proximo { get; set; }


        /// <summary>
        /// Referência para o nó (elemento) anterior na lista
        /// </summary>
        public NoLista anterior { get; set; }

        /// <summary>
        /// Construtora da classe NoLista
        /// </summary>
        public NoLista()
        {
            informacao = -1;
            proximo = null;
            anterior = null;
        }


    }
}
  • What would be "List"?

  • Your examples this obscure, you are treating your vestments as objects and talking in lists ... could explain better ?

  • @Marconciliosouza is a list that he himself implemented, very likely.

  • @LINQ that same friend, you understood me. However not being able to concatenate, has any solution for me?

  • @user89590 I don’t know what you mean by concatenate, actually, I didn’t understand any of your question. If you [Dit] and make your problem clear, I’m sure I can help you, without it I can’t.

  • @user89590 Now I get the idea. It has how to [Edit] and put the structure of your list?

  • @LINQ Done look there

  • @user89590 And the class noList, please

Show 3 more comments

1 answer

7


This can be done in two different ways.

The first is to concatenate the nodes of the second list in the first, that is, modify the first list and add all nodes of the other list. This would be more interesting if it were an internal method of Lista.

The code would be like this:

public void Concat(Lista toConcat)
{
    var no = InicioLista;

    while(no.proximo != null){
        no = no.proximo;
    }

    no.proximo = toConcat.InicioLista;
    toConcat.InicioLista.anterior = no;
}

The second way to do this is by creating a third list, which has all the elements of the previous two. To do this there is not much mystery, you will need to go through all the elements of the two lists and add them in another.

The code could be like this:

public static Lista Concatenar (Lista l1, Lista l2) 
{
    var novaLista = new Lista();
    Add(novaLista, l1);
    Add(novaLista, l2);
    return novaLista;
}

private static void Add(Lista nova, Lista velha)
{
    NoLista p = velha.InicioLista;      
    nova.Add(p.informacao);   

    while (p.proximo != null) {
        p = p.proximo;          
        nova.Add(p.informacao);
    }
}

See both versions working on . NET Fiddle.

  • If you don’t mind the structure of the original lists, the first method is more performatic.

  • 1

    @Jeffersonquesado E consumes less memory. Although this is not a problem nowadays xD

  • I found it interesting by this observation to chance someone falls by parachute without greater knowledge and be thinking "Oh, but how silly this first method if I can use the second is to continue with the same structure". And on memory, more pure truth! First method, extra memory o(0) (nor o(1) which is constant, but o(0) because it doesn’t use anything at all); second method, extra memory o(|a| + |b|)

Browser other questions tagged

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