简体   繁体   English

在Java中删除LinkedList中的节点

[英]Removing nodes in LinkedList in Java

Okey, so I understand the basics of Linked Lists. Okey,所以我了解链接列表的基础。 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. 在我的方法中,我只是制作了一个nextPerson的临时变量,并且按照正确的逻辑,我要删除该节点,但是此后我不会在“全局” nextPerson中进行任何更改。 The thing is.. It apperently affects firstPerson anyways and is actually removing that same node from firstPerson. 事实是。它无论如何都会影响firstPerson,实际上是从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因为它们都引用内存中的同一对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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