[英]removing the last node from singly linked list (java)
我的方法int deletLast()应该删除最后一个节点,并返回要删除的节点内部的值。 我的代码似乎不起作用。 它不会删除最后一个节点。 任何帮助将不胜感激。
导入java.util.NoSuchElementException; 导入java.util.Scanner;
公共类LinkedList11 {//私有内部类Node
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 = null; //给出错误”给出了不可访问的信息,因为您在上面有一个return语句,因此显然无法访问
`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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.