0

So this is my linked list class:

public class Main {

public LNode head = null;
class LNode<Object> {
    private Object data;
    private LNode<Object> next;

    public LNode(Object data) {
        this.data = data;
        this.next = null;
    }
}
public Object addAtEnd(Object data) {
    LNode<Object> newNode = new LNode<Object>(data);


    if (this.head == null) {

        this.head = newNode;
    } else {
        LNode<Object> currentNode = this.head;

        while (currentNode.next != null) {
            currentNode = currentNode.next;
        }
        currentNode.next = newNode;
    }
    return data;
}

public Object deleteData(Object data) {
    System.out.println("Deleting " + data + " from the list");

    if (this.head == null) {
        System.out.println("The List is empty!\n");
    }

    LNode<Object> currentNode = this.head, prevNode = this.head;

    if (this.head.data == data) {
        this.head = this.head.next;
    }


    while (currentNode != null && currentNode.data != data) {
        prevNode = currentNode;
        currentNode = currentNode.next;
    }

    if (currentNode != null) {
        prevNode.next = currentNode.next;
    } else {
        System.out.println("The data "+data+" could not be found in the List");
    }
    return data;
}

public void display() {
        if (this.head == null) {
            System.out.println("The List is empty.");
        } else {
            System.out.println("Current list content:");
            LNode<Object> currentNode = this.head;
            while (currentNode != null) {
                System.out.print(currentNode.data + " —> ");
                currentNode = currentNode.next;
            }
            System.out.println("NULL\n");
        }
    }

And if I do this in my main code,

    Main LL = new Main();
    String fname = "John";
    String lname = "Doe";
    String data=fname+" "+lname;
    LL.addAtEnd(data);
    LL.display();
    LL.deleteData("John Doe");

The output would be:

Current list content:
John Doe —> NULL

Deleting John Doe from the list
The data John Doe could not be found in the List

It says data could not be found but it is exactly the same as the added data using the add method. It is just quite weird for me because it only does this when the parameter for deleteData method involves a concatenated variable like the one above, unlike when I do this:

    Main LL = new Main();
    String name = "John Doe";
    String data = name;
    LL.addAtEnd(data);
    LL.display();
    LL.deleteData("John Doe");

Output:

Current list content:
John Doe —> NULL

Deleting John Doe from the list

It works fine and the method deletes the node normally. I would like to know what is wrong with my linked list class code since I am quite confident the issue resides there.

Knouki
  • 15
  • 6

0 Answers0