繁体   English   中英

从Java中的链接列表中删除head

[英]Removing head from a linked list in Java

这应该是一个相当基本的问题,但是我无法一生解决这个问题。 我使用的是我的讲师给我的两个文件,我必须编写一个removeFirst方法,该方法将从声明的链接列表中删除该head并返回该旧的head值。 它不能接受任何参数。 这是文件1文件2

我的removeFirst和调试代码如下。 我不知道如何在不能将aList用作参数的情况下引用aList ,尤其是因为链接列表不是全局的。 当我使用调试代码时,它打印aList ,然后打印21 (它应该删除的列表的头,这是removeFirst应该返回的内容),但是然后它不打印更新的链接列表-只是空白。

removeFirst代码:

public IntNode removeFirst() {
    IntNode cur = getHead();

    head = cur.getNext();
    head.setPrev(null);

    cur.setNext(null);

    return cur;
}

调试代码(位于main底部):

for(int i = 0; i < aList.size(aList.getHead()); i++) {
    aList.print(aList.findObject(i));
}

aList.print(aList.removeFirst());
System.out.println("");

for(int j = 0; j < aList.size(aList.getHead()); j++) {
    aList.print(aList.findObject(j));
}

你需要return head; 而不是return cur;

编辑抱歉。 我显然误解了您的问题陈述。 如果应该使用removeFirst()方法返回列表的 removeFirst() ,则上述内容是合适的。 如果应该返回已删除的元素(在注释和原始帖子的编辑后现在已经很清楚了),那么它应该可以正常工作。

大概removeHead()是列表类中的实例方法。 你并不需要传递一个参数,因为该列表可作为this方法里面。

查看aList的类定义会有所帮助。 您的file 1链接说它是指向MyLinkedList.java的,但是粘贴的代码是针对IntNode.java的。

编辑2我认为问题可能是您的调试代码。 findObject(j)不返回列表的 j 元素,而是返回包含j作为值的列表元素。 从代码中,看起来MyLinkedList.print(IntNode)从指定的节点开始打印整个列表。 如果将调试代码中的for循环简单地替换for

aList.print(aList.getHead());

我认为除了退货以外,您一切都很好。 您需要返回head代替cur因为cur表示已移除的head节点(上一个节点)。

public IntNode removeFirst() {
    IntNode cur = getHead();

     head = cur.getNext();
     head.setPrev(null);

     cur.setNext(null);

     return head;
 }

编辑:由于您已经更新了您的问题,这是您的第二个问题的答案;

您可以使用this运算符引用aList

更新:我在MyLinkedList类中添加了removeFirst()方法,然后在您的方法中添加了这些thwo语句(最后)

    aList.removeFirst();
    aList.print(aList.getHead());
    System.out.println("");

它可以正常工作,并将输出打印为:

    84 88 92 96 100 
    100 96 92 88 84 
    Size = 5
    Adding another IntNode
    21 84 88 92 96 100 
    Adding yet another IntNode
    21 52 84 88 92 96 100 
    The object is 92
    The object containing 50 was not found.
    The object removed has 96 in it.
    The object containing 50 was not found. Nothing was removed.
    21 52 84 88 92 100 
    Removing Head
    52 84 88 92 100 

我的假设是,由于您要通过引用访问所有对象因此在执行removeFirst()实质上就破坏了列表。

IntNode cur = getHead();

如同

cur = head;

由于它们可以在相同范围内访问。 通过在执行时执行以下操作:

head.setPrev(null);
...
cur.setNext(null);

您基本上是在这样做:

head.setPrev(null);
...
head.setNext(null);

要么....

null <-- head --> null

看到这是怎么回事?

您要做的是获取要删除的节点的副本,然后销毁该副本对列表的引用。

IntNode cur = new IntNode(getHead().getVal());

当您尝试从节点中删除旧的头时:

head.setNext(head.getNext());
head.setPrev(null);

暂无
暂无

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

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