我的方法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;
}
}
首先,如果 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 您需要查看前面的步骤,以检查下一个节点是否是最后一个节点,并从最后一个节点之前的节点中删除最后一个节点。希望你明白,我的意思,对错别字表示歉意
"return head.data;",该行位于您收到错误的位置正上方。"EAD = 空;给出错误" 给出无法访问,因为您在上面有一个返回语句,因此显然无法访问
'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;
}