我的方法int deletLast()应该删除最后一个节点,并返回被删除节点内的值。我的代码似乎不起作用。它不会删除最后一个节点。任何帮助将不胜感激。
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;
}
}
答案 0 :(得分:2)
首先,如果head是唯一的节点并且你想删除它,你需要设置head null。
if(head.link == null) {
int result = head .data;
head = null;
return result;
}
在检查head是否是唯一节点后尝试这样的事情:
Node current = head;
while (current.link.link != null)
current = current.link;
int result = current.link.data;
current.link = null;
return result;
Bc你需要查看前面的步骤,检查下一个节点是否是最后一个节点,并从最后一个节点之前删除最后一个节点。我希望你明白,我的意思和抱歉打字错误
答案 1 :(得分:0)
删除行"返回head.data;"就在您收到错误的地方正上方。 " ead = null; //给出错误"因为你上面有一个返回语句,因此显然无法访问
,因此无法访问`public int 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;
}