Click here to Skip to main content
14,332,489 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hello guys,

I have my methods to search, delete Start, delete End, Add Start, Add to End, but I have not been able to develop the methods to:

Search and Delete: the item searched
Insert element: Insert element in the position indicated by the user.

I hope you can help me with this methods, please.

Thanks in advance.

DS


What I have tried:

I share my methods and class

<pre lang="java">
//Node class
package asesorialistas;
/*@author Daniel Solis*/
public class Nodo{
    
public int Dato;
public Nodo Sig;//Puntero Enlcae recursivo
//Enlaza los diferentes nodos


//Constructor inicializar nodos
public Nodo(int d){
//Para crear un nodo final
this.Dato=d;  
}
//Constructor para insertar al inicio
public Nodo(int d, Nodo n){
this.Dato=d;
this.Sig=n;
    }
}

//List Methods
package asesorialistas;
/*@author Daniel Solis*/
public class Lista {
//Creando punteros
protected Nodo Inicio, Fin; //Punteros para saber donde inica y donde termina
//Donde esta el Inicio y Fin
public Lista(){
Inicio=null;
Fin=null;
    }
/*----------------------------------------------------------------------------*/
//Metodo para agregar al incio de la lista
public void AgregarInicio(int Elemento){
//Creando el nodo
Inicio = new Nodo(Elemento,Inicio);//Creando el Nodo
if(Fin==null){
    Fin=Inicio;
    }
}
/*----------------------------------------------------------------------------*/
//Metodo para agregar al final
public void AgrearFin(int Elemento){
    if (!EstaVacia()) {
      Fin.Sig=new Nodo(Elemento);
      Fin=Fin.Sig;   
    }else{
        Inicio=Fin=new Nodo(Elemento);
    }
}
/*----------------------------------------------------------------------------*/
//Metodo para mostrar la lista
public void Mostrar(){
Nodo recorrer=Inicio;
while (recorrer!=null){
    System.out.print("["+recorrer.Dato+"]");
    recorrer=recorrer.Sig;
    }
}
/*----------------------------------------------------------------------------*/
//Metodo esta la lista Vacia
public boolean EstaVacia() {
    return Inicio==null;  
}
/*----------------------------------------------------------------------------*/
public int BorrarInicio(){
        //creando el nodo
        int Elemento = Inicio.Dato;
        if(Inicio==Fin){
            Inicio = Fin = null;
        }
        else{
            Inicio=Inicio.Sig;
        }
        return Elemento;
}
/*----------------------------------------------------------------------------*/
public int BorrarFinal(){
        int Elemento = Fin.Dato;
        if(Inicio==Fin){
            Inicio = Fin = null;
        }else{
            Nodo temporal = Inicio;
            while(temporal.Sig != Fin){
                temporal = temporal.Sig;
            }
            Fin = temporal;
            Fin.Sig = null;
        }
        return Elemento;
}
/*----------------------------------------------------------------------------*/
public boolean BuscarElemento (int elemento){
    Nodo temporal=Inicio;
    while (temporal!=null&& temporal.Dato!=elemento)
    {
    temporal=temporal.Sig;
    }
    return temporal!=null;
    }

public boolean BuscarElementoEsp (int elemento){
    Nodo temporal=Inicio;
    while (temporal!=null&& temporal.Dato!=elemento)
    {
    temporal=temporal.Sig;
    }
    return temporal!=null;
    }
}

//MAIN
package asesorialistas;
import java.awt.HeadlessException;
import javax.swing.JOptionPane;
/*@author Dany*/
public class Principal {
    public static void main(String[] args) {
        //crear instancias de las clases
        Lista Listita = new Lista();
        //menu do while
        int opcion = 0;
        int Elemento; //valor a la lista (para insertar)
        
        do {
            try {
                opcion = Integer.parseInt(JOptionPane.showInputDialog(null, "***  MENU DE OPCIONES  ***\n"
                        + "1.- Agregar un Elemento al Inicio \n"
                        + "2.- Agregar un Elemento al Final \n"
                        + "3.- Mostrar los Elementos de las listas \n"
                        + "4.- Checar si la lista esta vacia \n"
                        + "5.- Borrar Elemento al inicio \n"
                        + "6.- Borrar Elemento al final \n"
                        + "7.- Buscar Elemento \n"
                        + "8.- Buscar Elemento y eliminar elemento \n"
                        + "9.- Salir \n"));

                switch(opcion){
                    
                    case 1:
                        try {
                            Elemento = Integer.parseInt(JOptionPane.showInputDialog(null, "Ingresa el Elemento "
                                    + "al inicio"));
                            Listita.AgregarInicio(Elemento);
                        } catch (NumberFormatException e) {
                            JOptionPane.showMessageDialog(null,"Error"+e.getMessage());
                        }
                        break;
                        
                    case 2:
                                                try {
                           Elemento = Integer.parseInt(JOptionPane.showInputDialog(null, "Ingresa el Elemento "
                                    + "al final"));
                            Listita.AgrearFin(Elemento); 
                        } catch (NumberFormatException e) {
                            JOptionPane.showMessageDialog(null,"Error"+e.getMessage()); 
                        }
                        break;
  
                    case 3:
                        Listita.Mostrar();
                        System.out.println("");
                        break;
                       
                    case 4:
                        Listita.EstaVacia();
                        break;
                        
                    case 5:
                        try {
                            Elemento = Listita.BorrarInicio();
                            JOptionPane.showMessageDialog(null, "El Elemento eliminado es: "
                                    +Elemento,"Eliminando nodo de inicio",
                                    JOptionPane.INFORMATION_MESSAGE);
                            
                        } catch (NumberFormatException e) {
                            JOptionPane.showMessageDialog(null,"Error"+e.getMessage());
                        }
                        break;
                        
                     case 6:
                        try {
                            Elemento = Listita.BorrarFinal();
                            JOptionPane.showMessageDialog(null, "El Elemento eliminado es: "
                                    +Elemento,"Eliminando nodo de fin",
                                    JOptionPane.INFORMATION_MESSAGE);
                            
                        } catch (NumberFormatException e) {
                            JOptionPane.showMessageDialog(null,"Error"+e.getMessage());
                        }
                        break;
                        
                        case 7:
                            Elemento=Integer.parseInt(JOptionPane.showInputDialog(null,"Ingresa el "+" elemento a buscar...","Buscando nodos en la lista",
                                    JOptionPane.INFORMATION_MESSAGE));
                            if (Listita.BuscarElemento(Elemento)==true) {
                            JOptionPane.showMessageDialog(null, "El elemento " + Elemento + " si esta en la lista",
                                        "nodo encontrado",JOptionPane.INFORMATION_MESSAGE);  
                            }else{JOptionPane.showMessageDialog(null, "El elemento " + Elemento + " no esta en la lista",
                                        "nodo no encintrado",JOptionPane.INFORMATION_MESSAGE);       
                            }   
                        break;
                        
                        case 8:
                            Elemento=Integer.parseInt(JOptionPane.showInputDialog(null,"Ingresa el "+" elemento a buscar...","Buscando nodos en la lista",
                                    JOptionPane.INFORMATION_MESSAGE));
                            if (Listita.BuscarElemento(Elemento)==true) {
                            int resp = JOptionPane.showConfirmDialog(null, "El elemento " + Elemento + " si esta en la lista quieres eliminarlo");
                                    if (JOptionPane.OK_OPTION == resp){
                                            System.out.println("Eliminar registro");
                                            }else{System.out.println("No Eliminar");
                                        }
                            }else{JOptionPane.showMessageDialog(null, "El elemento " + Elemento + " no esta en la lista",
                                        "nodo no encintrado",JOptionPane.INFORMATION_MESSAGE);       
                            }   
                        break;      
                }
            } catch (HeadlessException | NumberFormatException e) {
                JOptionPane.showMessageDialog(null,"Error"+ e.getMessage());
            }
        } while (opcion != 9);
        
    }
}


Case eight, is for search and delete. I do not finish it yet.
Posted
Updated 28-Nov-18 19:22pm

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.

Try it yourself, you may find it is not as difficult as you think! You have the code for searching, you have the code for deleting: put them together!

If you meet a specific problem, then please ask about that and we will do our best to help. But we aren't going to do it all for you!
   
Comments
Dani Solis 29-Nov-18 10:03am
   
Hello I'm sorry
I was not my intention, I are try in develop the project.

I was working last night in the method of insert per reference, but yet not still can not finish.

public void InsPorReferencia(int Elemento){
// Define new node.
Nodo Nuevo = new Nodo(Elemento,Referencia);
//Add value to the node.
Nuevo=Nuevo.Sig;
// Verify if the list has elements
if (!EstaVacia()) {
// Make a copy of the list.
Nodo temporal= Inicio;
// Scroll through the list until it reaches the reference node.
while (temporal.Dato!= Referencia) {
temporal = temporal.Sig;
}
// Create a backup of the list.
Nodo Sig = temporal.Sig;
// Link to the new node after the reference node.
temporal.Sig=Nuevo;
// Join the continuity of the list to the new node..
Nuevo.Sig=Sig;

// Aumentar el contador de tamaño de lista..
tamanio++;
}
}
}

Can you see error in this method?

Thanks

DS
OriginalGriff 29-Nov-18 10:14am
   
What does the debugger show you?
Dani Solis 29-Nov-18 11:08am
   
I get error in the method, not in in debugger

This it's error in the line 102 cicle While:

bad operand types for binary operator "! ="
first type int
second type: Node
OriginalGriff 29-Nov-18 11:15am
   
Well, read the error message!
What is it telling you?
Simple: you are trying to compare two different types, specifically an integer (temporal.Dato) with a Node (Referencia).

That's like comparing an Apple and a Sheepdog!

At a guess, you wanted to compare this:

while (temporal != Referencia) {

Or this:

while (temporal.Dato!= Referencia.Dato) {

But it's your code, not mine! (I'd also have some null checking in there as well)
Dani Solis 29-Nov-18 12:01pm
   
Yes, you have reason, I corrected the error and I ran program and get follow error.

Exception in thread "main" java.lang.NullPointerException
at asesorialistas.Lista.InsPorReferencia(Lista.java:106)
at asesorialistas.Principal.main(Principal.java:98)
C:\Users\Dani\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 20 seconds)

which is why I think my method is wrong structured

my method this is so:
public void InsPorReferencia(int Elemento){
// Define new node.
Nodo Nuevo = new Nodo(Elemento,Referencia);
//Add value to the node.
Nuevo=Nuevo.Sig;
// Verify if the list has elements
if (!EstaVacia()) {
// Make a copy of the list.
Nodo temporal= Inicio;
// Scroll through the list until it reaches the reference node.
while (temporal != Referencia) {
temporal = temporal.Sig;
}
// Create a backup of the list.
Nodo Sig = temporal.Sig;
// Link to the new node after the reference node.
temporal.Sig=Nuevo;
// Join the continuity of the list to the new node..
Nuevo.Sig=Sig;

// Aumentar el contador de tamaño de lista..
tamanio++;
}
}
}

Class Main

case 8:
Elemento=Integer.parseInt(JOptionPane.showInputDialog(null,"Ingresa el "+" elemento despues de ","el elemento",
JOptionPane.INFORMATION_MESSAGE));
if (Listita.BuscarElemento(Elemento)==true) {
/*JOptionPane.showMessageDialog(null, "El elemento " + Elemento + " si esta en la lista",
"nodo encontrado",JOptionPane.INFORMATION_MESSAGE); */
Listita.InsPorReferencia(Elemento);
}else{JOptionPane.showMessageDialog(null, "El elemento " + Elemento + " no esta en la lista",
"nodo no encontrado",JOptionPane.INFORMATION_MESSAGE);
}
break;
OriginalGriff 29-Nov-18 12:12pm
   
Now what did I say at the end of the last message? Oh yes: "I'd also have some null checking in there as well"

Now you see why ... :laugh:
Dani Solis 29-Nov-18 12:45pm
   
I not understand, "I'd also have some null checking "

please could you explain me?

OriginalGriff 29-Nov-18 13:56pm
   
What value is at the end of your linked list?
What value is at the head of an empty linked list?

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100