简体   繁体   中英

Removing nodes in LinkedList in Java

Okey, so I understand the basics of Linked Lists. I know how each node has a reference to the next node, and I get it how it's all tied up.

My code is working with no issues, but the issue is I just don't get how it's working (yeah...)

My question is about removing a node in the linked list. So let's say I'm removing a Person in my list, which is in the middle of the list. In my method, I'm just making a temp variable of nextPerson, and with the right logic, I'm deleting that node, BUT I'm NOT changing anything in the "global" nextPerson afterwards. The thing is.. It apperently affects firstPerson anyways and is actually removing that same node from firstPerson.

I know linked list are confusing, and so is my question. But if there's anything I'm not clear about, I can explain further..

  public class Store
{
    private Person firstPerson;

    void newPerson(Person person)
    {
    if (firstPerson == null)
    {
        firstPerson = person;
    }
    else
    {
        person.nextPerson = firstPerson;
        firstPerson = person;
    }
}

void checkout()
{
    Person temp = firstPerson;
    while (temp.nextPerson != null)
    {
        System.out.println(temp.getName() + " bought" + temp.getItem() + ".");
        System.out.println("- Hade bra!");
        temp = temp.nextPerson;
    }
}

//THIS METHOD:
boolean deletePerson(String name)
{


    Person temp = firstPerson;
    if (temp.getName().equals(name))
    {
        temp = temp.nextPerson;
    }
    else
    {
        while (temp.nextPerson != null)
        {
            if (temp.nextPerson.getName().equals(name))
            {
                //REMOVING THE NODE
                temp.nextPerson = temp.nextPerson.nextPerson;
                //NOT CHANGING ANYTHING IN "firstPerson", STILL CHANGES IT
                return true;
            }
            else
            {
                temp  = temp.nextPerson;
            }
        }
    }
    return false;

    }
}



 public class Person
{
private String name, item;
Person nextPerson;

Person(String name, String item)
{
    this.name = name;
    this.item = item;
}

public String getItem()
{
    return item;
}

public String getName()
{
        return name;
    }
}

在Java中,包含对象的变量实际上包含对对象的引用,因此,当您将temp分配给firstperson ,每次使用temp都等同于使用firstperson因为它们都引用内存中的同一对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM