My method int deletLast() should delete the last node as well as return the value inside the node being deleted. my code does not seem to work. it does not delete the last node. any help will be greatly appreciated.
import java.util.NoSuchElementException; import java.util.Scanner;
public class LinkedList11 { // Private inner class 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;
}
}
2 Answers 2
first, if head is the only node and you want to remove it, you'll need to set head null.
if(head.link == null) {
int result = head .data;
head = null;
return result;
}
Try something like this after checking if head is the only node:
Node current = head;
while (current.link.link != null)
current = current.link;
int result = current.link.data;
current.link = null;
return result;
Bc you need to look to steps ahead to check if next node is last one and remove last from the one before the last. I hope you understand,what I meant and sorry for typos
1 Comment
remove line "return head.data;" which is right above where you get the error. "ead = null; //gives error " gives unreachable because you have a return statement right above, so it is obviously unreachable
`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
{
// 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;
}