I am practicing working with Linked List Nodes and have come upon a problem I don't know how to answer. How do you go about deleting the last node in a linked list. The code below works for all entry's bar the last node. The last does not get deleted.
Node Class
public class Node {
private String data;
private Node next;
Node(String data, Node next)
{
this.data = data;
this.next = next;
}
public void setData(String d)
{
data = d;
}
public void setNext(Node n)
{
next = n;
}
public String getData()
{
return data;
}
public Node getNext()
{
return next;
}
Main
Node list = new Node("NODE 1",new Node("NODE 2",new Node("NODE 3", null)));
list = insertSecond(list,"New Node");
list = addLast(list,"LAST NODE");
printList(list);
System.out.println();
deleteNode(list,"LAST NODE");
printList(list);
}
public static Node deleteNode(Node list,String str)
{
Node temp = list;
Node prev = list;
while(temp.getNext() != null)
{
if(temp.getData().equals(str))
{
if(prev.getNext() == null)
prev.setNext(null);
else{
prev.setNext(prev.getNext().getNext());
}
}
prev = temp;
temp = temp.getNext();
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…