簡體   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