我的方法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;
}
}
非常感謝你的解釋。只是測試它,工作。 – 2014-12-11 21:09:13