2014-12-10 344 views
1

我的方法int deletLast()應刪除最後一個節點,並返回被刪除節點內的值。我的代碼似乎不工作。它不會刪除最後一個節點。任何幫助將不勝感激。從單向鏈表中刪除最後一個節點(java)

import java.util.NoSuchElementException; import java.util.Scanner;

公共類LinkedList11 { //私人內部類節點

private class Node{ 
    int data; 
    Node link; 


    public Node(){ 
     data = Integer.MIN_VALUE; 
     link = null; 
    } 

    public Node(int x, Node p){ 
     data = x; 
     link = p; 
    } 
} 
// End of Node class 

public Node head; 

public LinkedList11(){ 
    head = null; 
} 

public int deleteLast() throws NoSuchElementException { 


    if (head == null) //handle when list is empty 
    { throw new NoSuchElementException();} 

    if(head.link == null) //handle when head is the only node 
    { return head.data; 


     } 

     Node position = head; 
     Node temp = head; //temp has to be initialized to something 
     int dataAtEnd =0; 
     while (position != null) 
     { dataAtEnd = position.data;  
      temp =position;    //safe keep current position 
      position = position.link;  //update position pointer to get the next value 
      } 

     position =temp; // store current position in next position 
     return dataAtEnd; 

} 

}

回答

2

首先,如果head是唯一的節點,並且想要將其刪除,則需要將head設置爲null。

if(head.link == null) { 
    int result = head .data; 
    head = null; 
    return result; 
} 

嘗試是這樣的檢查後,如果頭是唯一的節點:

Node current = head; 
while (current.link.link != null) 
    current = current.link; 
int result = current.link.data; 
current.link = null; 
return result; 

BC你需要尋找到步驟提前檢查,如果下一個節點是最後一個和最後一個從之前的一個刪除最後。我希望你明白,我的意思是對錯別字

+0

非常感謝你的解釋。只是測試它,工作。 – 2014-12-11 21:09:13

0

刪除線 「返回head.data;」這正是你發現錯誤的地方。 「EAD = NULL; //提示錯誤」 給出了訪問,因爲你有一個return語句正上方,因此它顯然是不可達

`公衆詮釋deleteLast()拋出NoSuchElementException異常{

if (head == null) //handle when list is empty 
{ throw new NoSuchElementException();} 

if(head.link == null) //handle when head is the only node 
{ 
    // You must store the data somewhere since head has to be set to NULL. 
    int dataToReturn = head.data; 

    // Since head is the only node, set it to NULL now. 
    head = null; 

    // Now return the data the the last node (head in this case) contained. 
    return dataToReturn; 
    } 

    Node position = head; 
    Node temp = head; //temp has to be initialized to something 
    int dataAtEnd =0; 

    while (position.link != null) 
    { dataAtEnd = position.data;  
     temp =position;    //safe keep current position 
     position = position.link;  //update position pointer to get the next value 
     } 

    position = null; 
    temp.link = null;//this is what deletes the last node. 

    return dataAtEnd; 

}

+0

感謝但它仍然不刪除最後一個節點 – 2014-12-10 23:18:09

+0

看到我的編輯。我沒有測試它,但它應該爲你解決它。最大的問題是你沒有將temp.link設置爲null。 – RAEC 2014-12-11 13:43:59

+0

非常感謝您的評論。他們幫助澄清事情。只有一個小錯誤,儘管代碼刪除了最後一個節點,但它沒有顯示正在刪除的正確值。 – 2014-12-11 21:07:59