Calgar99 Calgar99 - 1 month ago 18
Java Question

Delete Last Node of a Linked List

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();
}

Kai Kai
Answer

I would guess while(temp.getNext() != null) fails for your last element. The last element won't have a next element. So the last element is not compared against the passed string. You should trace this with the debugger.